Wrap input's label in hyperlink anchor tag

2019-08-23 03:24发布

问题:

I'm trying to click a radio button's label, select that radio option and use an on-page anchor to scroll to the appropriate div.

Any chance I can do this without js? I can't seem to get it to work. Either the anchor works or the label works.

JSFiddle - http://jsfiddle.net/mfVJ5/

<input type="radio" name="name" id="name" value="1" class="name">
<a href="#gosomewhere" class="btn">
  <label for="name">
    Click to Select Option
  </label>
</a>

<div id="gosomewhere">And I'm here.</div>

回答1:

Nesting a label element inside an a element is not formally forbidden in HTML 4, but neither is its meaning well-defined. It is undefined what happens when the inner element is clicked on. In HTML5 CR, the a element is for such reasons defined so that no interactive descendant is allowed, and label counts as interactive.

The best approach is to differentiate the actions, associating them with different elements. It would be poor usability to have a radio button label that has both the expected effect (toggling the button setting) and some completely different effect. But it is not possible to suggest some specific coding, since problem is incompletely defined. For one thing, radio buttons are normally used in groups, and it is unclear whether this radio button really appears as standalone.



回答2:

Unsure why not wish to use js/jQuery - code is minimal. It would look like this:

jsFiddle Demo

$(function() {
    $('#name').click(function() {
        $('html, body').animate({scrollTop:$('#gosomewhere').offset().top}, 500);
    });
});

And, of course, you must reference the jQuery library in the <head> tags, like this:

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>