Wrap input's label in hyperlink anchor tag

2019-08-23 02:37发布

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>

2条回答
够拽才男人
2楼-- · 2019-08-23 03:10

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.

查看更多
家丑人穷心不美
3楼-- · 2019-08-23 03:27

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>
查看更多
登录 后发表回答