[英]jquery smooth scrolling issue
我有一个jQuery问题,我需要一些帮助,但似乎找不到解决我问题的任何结果。 我有一个1页的网站,该网站使用下面的jquery平滑滚动以定位链接。 唯一的问题是,当它在移动设备上时,我需要将滚动条调整为最大-170px的赤字。 如何仅使用以下相同功能定位移动查询?
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 700);
return false;
}
}
});
});
您可以检查屏幕宽度,如果它小于特定宽度(例如320),则可以考虑所需的额外滚动偏移量:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
var winWidth = $(window).width();
if( winWidth > 320 )
{
$('html, body').animate({
scrollTop: target.offset().top
}, 700);
}
else
{
$('html, body').animate({
scrollTop: target.offset().top - 170
}, 700);
}
return false;
}
}
});//click
});//ready
我可以为您提供2种选择:
您可以加载JS库,以检查您所使用的浏览器/设备。 https://github.com/rafaelp/css_browser_selector 。 这会在HTML元素上加载一个类,您可以像这样检查函数:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
if($('html').hasClass('mobile')) {
$('html, body').animate({
scrollTop: target.offset().top - 170
}, 700);
} else {
$('html, body').animate({
scrollTop: target.offset().top
}, 700);
}
return false;
}
}
});
});
或者,您可以检查窗口大小以检查它是否小于平板电脑:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
if($(window).width() < 768) {
$('html, body').animate({
scrollTop: target.offset().top - 170
}, 700);
} else {
$('html, body').animate({
scrollTop: target.offset().top
}, 700);
}
return false;
}
}
});
});
这对我来说很好,通过id正确,它正常工作
ele.on('click',function(){
$('html, body').animate({scrollTop: $("#"+id).offset().top}, 750);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.