我该如何使用jQuery检查浏览器是否支持position:fixed
?我认为我需要使用$.support
,但怎么做呢?
感谢您的时间。
我该如何使用jQuery检查浏览器是否支持position:fixed
?我认为我需要使用$.support
,但怎么做呢?
感谢您的时间。
最可靠的方法是进行实际的特性测试。浏览器嗅探(Browser sniffing)是脆弱而不可靠的。
我在CFT中有这样一个测试示例:http://kangax.github.com/cft/#IS_POSITION_FIXED_SUPPORTED。注意,该测试应在加载document.body
后运行。
我发现移动版Safari(具体来说是通过OSX上的iOS模拟器使用的iOS 4.2)除非等待几毫秒,否则无法滚动到任何地方。因此,出现了误报。
我写了一个快速的jQuery插件来解决这个问题:
(function($) {
$.support.fixedPosition = function (callback) {
setTimeout(
function () {
var container = document.body;
if (document.createElement && container && container.appendChild && container.removeChild) {
var el = document.createElement('div');
if (!el.getBoundingClientRect) return null;
el.innerHTML = 'x';
el.style.cssText = 'position:fixed;top:100px;';
container.appendChild(el);
var originalHeight = container.style.height,
originalScrollTop = container.scrollTop;
container.style.height = '3000px';
container.scrollTop = 500;
var elementTop = el.getBoundingClientRect().top;
container.style.height = originalHeight;
var isSupported = !!(elementTop === 100);
container.removeChild(el);
container.scrollTop = originalScrollTop;
callback(isSupported);
}
else {
callback(null);
}
},
20
);
}
})(jQuery);
function fixedcheck () {
var fixedDiv = $('<div>').css('position', 'fixed').appendTo('body');
var pos1 = fixedDiv.offset().top;
$(window).scrollTop($(window).scrollTop() + 1);
var pos2 = fixedDiv.offset().top;
fixedDiv.remove();
return (pos1 != pos2)
}
/* Usage */
$(document).ready(function () {
if (!fixedcheck()) alert('Your browser does not support fixed position!')
});
<html>
<script type="text/javascript">
test = function() {
if(!!document.getElementById("test").style.position) {
alert('true');
}
else{
alert('false');
}
}
</script>
<body>
<p id="test" onclick="test();" style="position:fixed;">Hi</p>
</body>
</html>
由于所有主流浏览器都支持 position 属性,因此这将始终返回 true。我想没有办法检查 position 可能的值,所以您必须检查用户正在查看您的页面的浏览器及其版本,就像 Paolo Bergantino 所说的那样。
我创建了另一个检查浏览器是否真正支持position:fixed
的方法。它创建了一个固定的div并尝试滚动并检查div的位置是否改变。
function isPositionFixedSupported(){
var el = jQuery("<div id='fixed_test' style='position:fixed;top:1px;width:1px;height:1px;'></div>");
el.appendTo("body");
var prevScrollTop = jQuery(document).scrollTop();
var expectedResult = 1+prevScrollTop;
var scrollChanged = false;
//simulate scrolling
if (prevScrollTop === 0) {
window.scrollTo(0, 1);
expectedResult = 2;
scrollChanged = true;
}
//check position of div
suppoorted = (el.offset().top === expectedResult);
if (scrollChanged) {
window.scrollTo(0, prevScrollTop);
}
el.remove();
return suppoorted;
}
此函数已在Firefox 22、Chrome 28、IE 7-10和Android浏览器2.3中进行了测试。
position:fixed
显然在移动版 Safari(4.3.2)中适用于除 body 以外的所有块级元素,因此 CFT 的答案(http://kangax.github.com/cft/#IS_POSITION_FIXED_SUPPORTED)应该包含以下内容:
var isSupported = (container.scrollTop === 500 && elementTop === 100);