天天看点

手机端背景图固定fixed兼容方法

背景图background-attachment:fixed在移动端多为不支持,采用position: fixed;并JS来解决

.box{width: 100%;height: 100%;}
.fixedbg{position: fixed;left: 0;top: 0;z-index: -1; width: 100%;height: 100%;}

<div class="box"><div class="fixedbg">图片1</div></div>
<div class="box"><div class="fixedbg">图片2</div></div>
<div class="box"><div class="fixedbg">图片3</div></div>
           
window.onscroll = function(){
	//滚屏时固定背景的遮罩
	document.querySelectorAll('.fixedbg').forEach(function(pre){
		var bound = pre.parentElement.getBoundingClientRect();
		var clip = 'rect('+ [bound.top + 'px', pre.parentElement.clientWidth + 'px', bound.bottom + 'px', 0].join() +')';
		pre.style.clip = clip;
	})
}
           

来源:https://www.zhangxinxu.com/wordpress/2018/07/css-information-stream-advertisement/

继续阅读