[英]Smooth Scroll on selection change jquery
I am trying to scroll to the anchor smoothly on dropdown selection change. 我试图在下拉选择更改时平稳地滚动到锚点。 Tried a lot of code from other answers but couldnt get it to work since i have no experience with jquery.
从其他答案中尝试了很多代码,但由于我没有jquery的经验,因此无法正常工作。 Any help would be appreciated!
任何帮助,将不胜感激! PS : dont mind the link selector if statements
PS:不要介意链接选择器if语句
here is my dropdown 这是我的下拉菜单
<select class="form-control " id="dropDownSelect" onchange="location = this.value;">
<option value="#">Hotel Selection</option>
<option value="#ecoHotel">EcoName</option>
<option value="#luxuryHotel">LuxuryName</option>
</select>
and here is the jquery i am trying to implement in 这是我正在尝试实现的jQuery
<script>
$("#dropDownSelect").change(function() {
console.log(this.value);
// Here Should be my smoothscroll
if (this.value === "#luxuryHotel") {
$("#inqLink").attr('href', "http://www.google.com");
}
else{
$("#inqLink").attr('href', "package-dentmodern-hollywoodsmile-inquire.html");
}
});
</script>
$('html,body').animate({
scrollTop: $('#target').offset().top
}, 1000);
This will scroll smoothly to the DOM element with the targeted id
这将平滑滚动到具有目标
id
的DOM元素
1000
is in miliseconds. 1000
以毫秒为单位。
I've got another solution for you. 我为您提供了另一种解决方案。 Make your own
dropdown
, in this way it is more easy for you to achieve what you want. 制作自己的
dropdown
,通过这种方式,您可以更轻松地实现所需的目标。 I did all the drop down functions with JQuery
, you just have to style dropdown: 我使用
JQuery
完成了所有下拉功能,您只需要设置下拉样式的样式即可:
$(document).ready(function(){ $('.target-click').click(function(){ $('.hidden-drop').slideToggle(); }) $('nav li a').click(function(e) { setTimeout(function(){ $('.hidden-drop').slideUp(); }, 200); $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top }, 600); return false; }); });
select { margin-bottom: 30px; } #ecoHotel { background-color: lightgreen; } #luxuryHotel { background-color: lightgrey; } .page { display: block; height: 100vh; width: 100%; transition: all .3s ease; } .hidden-drop { display: none; } ul li { cursor: pointer; list-style: none; } ul { padding: 0; } span.target-click { color: #444; border: 1px solid #ddd; background-color: #f7f7f7; height: 44px; display: inline-block; line-height: 44px; padding-left: 10px; padding-right: 10px; }
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script> <nav> <ul> <li> <span class="target-click">Hotel Selection</span> <ul class="hidden-drop"> <li><a href="#ecoHotel">EcoName</a></li> <li><a href="#luxuryHotel">LuxuryName</a></li> </ul> </li> </ul> </nav> <div id="ecoHotel" class="page">Eco Hotel Section</div> <div id="luxuryHotel" class="page">Luxury Hotel Section</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.