javascript:window.scroll()函数behavior属性smooth属性值在iphone浏览器上不兼容
在制作静态页面的时候,使用window.scroll()来实现点击爬楼的事件,一开始是这样写的
let height = 500 //需要跳转到的高度
this.window.scroll({
“top”:height,
“behavior”:“smooth”
})
在安卓手机的浏览器上是可以实现的,但是一用苹果浏览器打开,当我点击触发事件时, “behavior”:"smooth"并没有起作用,网上查了下发现苹果浏览器不兼容这个属性。只能再想办法了。
解决方法
网上也查到了在VUE项目上的解决方法
链接: https://blog.csdn.net/qq_33505829/article/details/105442185
但是!!!!!!!
我做的只是个静态页面,并没有使用VUE项目架构,所以只能找js组件了
由于引入了Vue.js,于是先搞了几个网上找到的方法
// 获取当前滚动条高度
getScrollTop() {
let scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
//获取滚动条总高度
getScrollHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
然后就是最重要的组件
Math.easeInOutQuad = function(t, b, c, d) {
t /= d / 2
if (t < 1) {
return c / 2 * t * t + b
}
t–
return -c / 2 * (t * (t - 2) - 1) + b
}
// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
const requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
})()
// because it’s so fucking difficult to detect the scrolling element, just move them all
function move(amount) {
document.documentElement.scrollTop = amount
document.body.parentNode.scrollTop = amount
document.body.scrollTop = amount
}
function position() {
return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
}
function scrollToApi(to, duration, callback) {
const start = position()
const change = to - start
const increment = 20
let currentTime = 0
duration = typeof duration === ‘undefined’ ? 500 : duration
const animateScroll = function() {
// increment the time
currentTime += increment
// find the value with the quadratic in-out easing function
const val = Math.easeInOutQuad(currentTime, start, change, duration)
// move the document.body
move(val)
// do the animation unless its over
if (currentTime < duration) {
requestAnimFrame(animateScroll)
} else {
if (callback && typeof callback === ‘function’) {
// the animation is done so lets callback
callback()
}
}
}
animateScroll()
}
外部调用scrollToApi(to, duration, callback)
//to 目的高度
//duration 过程时间
//callback 回调函数
计算好你需要去的高度,然后直接调用完事!