gpt4 book ai didi

javascript - offset() 在移动浏览器中返回不同的值

转载 作者:行者123 更新时间:2023-12-03 07:14:02 25 4
gpt4 key购买 nike

我正在尝试相对于其目标动态定位弹出窗口。它在桌面浏览器中运行良好。但是在移动浏览器中,位置是错误的。这主要是因为,在桌面浏览器中,即使页面滚动,元素的 offset() 也会给出相同的值。但是在移动浏览器中,当页面滚动时,offset() 会提供不同的值。要获得实际的偏移量,我们需要这样做,

offset.left -= window.pageXOffset
offset.top -= window.pageYOffset

但这并非在所有情况下都会发生。仅当页面未在移动浏览器中缩放时才会发生这种情况。
此处报告了此问题( https://github.com/jquery/jquery/issues/3187)。
而在此问题页面中,他们提到仅在缩放移动浏览器时才会出现此问题。

无论桌面/移动/ipad浏览器如何找到正确的偏移量?

我已经得出了一个解决方案来获取元素的实际偏移量:
function getOffset( element ){
var $body = $('body');
var offset = element.offset();
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
var temp = $('<span>').css({
position:'absolute',
height:'20px',
width:'20px',
top:'0px',
left:'0px'
}).appendTo( $body );
correctionOffset = temp.offset();
correctionOffset.left = correctionOffset.left - parseFloat( $body.css('margin-left') ) - parseFloat( $body.css('border-left-width') ) ;
correctionOffset.top = correctionOffset.top - parseFloat( $body.css('margin-top') ) - parseFloat($body.css('border-top-width') ) ;
temp.remove();
offset.left -= ( correctionOffset.left );
offset.top -= ( correctionOffset.top );
}
return offset;
}

即使在缩放时,这是在移动浏览器中实现元素正确偏移的正确方法吗?

最佳答案

你可以试试这个它的工作:

<li><a href="#scroll_to_gallery" class="bnrbuttons"></a></li>


<script>
jQuery(document).on('click', '.bnrbuttons a', function(event){
event.preventDefault();

if ( $(window).width() < 767) { //Set here window width accourding to your need

jQuery('html, body').animate({
scrollTop: jQuery( jQuery.attr(this, 'href') ).offset().top + 230
}, 500);

}
else{
jQuery('html, body').animate({
scrollTop: jQuery( jQuery.attr(this, 'href') ).offset().top - 65
}, 500);
}

});

关于javascript - offset() 在移动浏览器中返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46102020/

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