可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I know I have to change the id into a val but how??? any idea? sorry, It might be so easy for you guys but not for me:-)
- each option scrollTo a specific tag, but on click doesn't work
http://jsfiddle.net/9w0L7fxb/
var body = $('html, body'); $('#London').on("click", function (e) { e.preventDefault(); body.animate({ scrollTop: slideMap.offset().top - 63 }, 'slow'); return false; }); $("option#London").change(function () { $(this).val(); });
http://jsfiddle.net/ym4frmp6/
回答1:
You should use change event.
var body = $('html, body'); $('.country-list').on("change", function () { // make sure, the val() is not empty: if($(this).val()){ body.animate({ scrollTop: $('#'+$(this).val()).offset().top - 63 }, 'slow'); } return false; });
JSFiddle
回答2:
here's the updated fiddle: http://jsfiddle.net/ym4frmp6/4/
$('.country-list').on("change", function (e) { e.preventDefault(); var selection = $(this).val(); alert(selection); });
the event is on change of the select, and you get the option value by calling $(this).val()
this solves the issue of the click event.
回答3:
Here's another approach, I think it's simpler : (run it directly below)
var $body = $('html,body'), $select = $('select.country-list'); $select.change(function (e) { var aTag = $("a[name='"+ e.currentTarget.value +"']"); $body.animate({scrollTop: aTag.offset().top - 40 },'slow'); });
body{ position: relative; height:100%;min-height:100%; } select{ position: fixed; } a{ display : block; margin-top : 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="country-list"> <option value="">select your city</option> <option value="London" >London</option> <option value="CapeTown" >Cape Town</option> <option value="Beijing" >Beijing</option> <option value="Tokyo" >Tokyo</option> <option value="HongKong" >Hong Kong</option> <option value="KualaLumpur" >Kuala Lumpur</option> <option value="Singapore">Singapore</option> <option value="Mumbai">Mumbai</option> <option value="Shanghai">Shanghai</option> <option value="Sydney">Sydney</option> </select> <br> <a href="#" name="London">London</a><br> <a href="#" name="CapeTown">CapeTown</a><br> <a href="#" name="Beijing">Beijing</a><br> <a href="#" name="Tokyo">Tokyo</a><br> <a href="#" name="HongKong">HongKong</a><br> <a href="#" name="KualaLumpur">KualaLumpur</a><br> <a href="#" name="Singapore">Singapore</a><br> <a href="#" name="Mumbai">Mumbai</a><br> <a href="#" name="Shanghai">Shanghai</a><br> <a href="#" name="Sydney">Sydney</a><br>
Edit
Changed $select.find('option:selected').val() into $(this).val(). It works because the "select" elements takes the value from its selected "option".
Edit 2
Simplified again by changing $(this).val() into e.currentTarget.value.