vbr*_*n27 5 html javascript css mobile jquery
我正在尝试相对于其目标动态定位弹出窗口。它在桌面浏览器中运行良好。但在移动浏览器中,这些位置是有问题的。这主要是因为,在桌面浏览器中,即使页面滚动,元素的 offset() 也会给出相同的值。但在移动浏览器中,当页面滚动时,offset() 会提供不同的值。为了获得实际的偏移量,我们需要这样做,
offset.left -= window.pageXOffset
offset.top -= window.pageYOffset
Run Code Online (Sandbox Code Playgroud)
但并非所有情况都会发生这种情况。仅当页面在移动浏览器中未缩放时才会发生这种情况。此处报告了此问题(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;
}
Run Code Online (Sandbox Code Playgroud)
即使元素被缩放,这是在移动浏览器中实现元素正确偏移的正确方法吗?
你可以试试这个,它的工作原理:
<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);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2072 次 |
| 最近记录: |