gpt4 book ai didi

javascript - 检测浏览器是否已经具有平滑滚动功能

转载 作者:行者123 更新时间:2023-12-01 05:30:40 26 4
gpt4 key购买 nike

当点击哈希链接时,我使用这段 JavaScript 为我的网站添加了平滑滚动功能。

$('a[href*=#]')
.click(onAnchorClick);

function onAnchorClick(event)
{
return ! scrollTo(this.hash);
}


function scrollTo(target)
{
var e = $(target);
var y = e.exists() ? e.offset().top : 0;

if(y == 0 && target != '#top')
return false;

if(Math.max($('html').scrollTop(), $('body').scrollTop()) != y)
$('html,body')
.animate({scrollTop: y}, 500, function() { location.hash = target; } );
else
location.hash = target;

return true;
}

$.fn.exists = function()
{
return this.length > 0 ? this : false;
}

在桌面浏览器中运行得非常好,看起来至少在 iOS 设备上也运行得很好。然而,在我的 WinPhone 8 设备上,它是垃圾。滚动很困惑,甚至没有到达应有的位置。因此,我决定不通过 if(!/Windows Phone 8\.0/.test(navigator.userAgent)) 启用它。

现在效果很好,而且似乎 WinPhone 上的浏览​​器默认情况下实际上是平滑滚动的,这很棒。

但是,如果浏览器默认情况下已经执行此操作,那么激活平滑滚动脚本当然有点愚蠢。有没有办法检测浏览器是否已启用平滑滚动功能?

最佳答案

我成功地解决了这个问题:

<style>
body {
scroll-behavior: smooth;
}
</style>

<script>
if(getComputedStyle(document.body).scrollBehavior === 'smooth'){
console.log('This browser supports scrollBehavior smooth');
}
</script>

关于javascript - 检测浏览器是否已经具有平滑滚动功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37667406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com