原生js实现网页侧边随页面滚动广告效果
css
/*测试用的高度*/html {height: 3000px;}#rightroll {position: absolute;}.close {position: absolute;right: 0;top: -10px;}.close img {width: 20px;height: 20px;}li {list-style: none;width: 80px;height: 80px;background-color: red;margin-top: 10px;}
html
<div id="rightroll"><div class="close" style="justify-content: flex-start;"><img class="close-img"src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAABD1JREFUWEfFV11oHFUU/s7sZk0W2/St2AdBLS1YfKoJVJG29qEqrVY06YMPvlQFhWB+7r27EnB86e7cyY8EFKw+CYIaQW2lVaGmBa2S2AeRCo2aQvGHvohsZBM2O3PkLrNhdzIzuyaRDOzD7D3nnu+c891zvyFs8UNbHB9tA5iamtpeLpcPENFBy7IOMvNOItppEmDmW0R0y/f9y8x8OZvNfjswMFBqJ7m2ADiO8yIRKQB3trMpgJvM7Cil3mxlnwjAtu10V1fXWSJ6NMh0nojOeZ73WSaT+aNarf5p/k+n03dUKpVdqVTqGDMfJ6I9gf2FpaWlx23brsYBiQXgum4/M38QOF4FcEZKeaZVRmZda/08APPbb96J6KQQ4sMo30gArus+zMwXA4dpKWV/O4HDNlprE7QvAHFECPFV2GYNgL6+vlRPT0+tZMz8mlLKXk/wuo/jODYRvWre5+bm0tPT017jfmsAuK6rmVkQUUEI8cpGgtd9Xdc9zcx5InKFEDIWQLFY7Lcsy/T9qpTy/s0IXt9Da/294YTv+ydzudwqH1YrMDk5uWNlZcWQ7W4AL4QJp7WeAXAbgGellD9HgZuYmNhdrVbfB7AopTzcaBMQ8y0ACx0dHfsHBwf/rnGjoVcniOhjADeklAZE06O1vgLggKlOpVJ5YnR09PdGA8dxdhHRpwBM5SIrqLVeAHAXMz+plPqkCYDrupPM/DKAd6SUz4UBjI2N3ev7vindPmb+OpPJHK9nYdv2jmw2exbAQwCuWZbVPzIy8lNEEm8DOEVErwshBsMAvmHmBzzPO5zP5y9FlbgRBIAvu7u7jxm7Uql0jpmPJgU3doVC4VAqlZohoitCiAebAGitfwFwTyqV2js8PDwfR8AQiFoZAZxoFdwYjY+P7/E87zqAX6WUu8MVWGTm25l5u1JqMekEhEAY09iyh3iyjYhKRPSPEGLbpgEgoh9M35MqZ4I5jhMPYJ0tuBZkuA/Ad8zcp5T6La56rVrwX0lYK7sJVj8dAGbS6fTTQ0NDf0WBSCSh4ziniShvuCKlHEk6huGehzhxvlwuP2Xb9nLEMRwDMMzMBaVUbcyvDqJisXjUsqzPmXleKbU3YRBFEi40Jz5SStVuwRAJrxut4Pv+I7lc7osmAEZyLS8v/xionthRbFnWqaghYzYLQLzbYhTf7OzsvK8u2Zpuw0B6vfF/XkbM/FKjVFtzHTuOcz6QYOsWIhHtqwkTZr6glHqscX0NAKMDs9nsijHabEFSLpc7wvowTpKt6sGNCJO6EKmRLUYXJonSRl24UVEaqQebTkHU4DD6sLe3t2AkWrB+A8BFz/Pei5HlzwA4Yu78IGt3dnY2H9aBiRyIAhJItUKglpLuqfragu/7+UbpFefU1peRcTaSrVKpHDKfZQB6oz7NAMyaz7NMJnOpLlZaoW0bQKuN1ru+5QD+BU1gXj+OyZS9AAAAAElFTkSuQmCC"alt=""></div><li></li><li></li><li></li></div>
js
var roll = document.getElementById('rightroll'),initX = 0,initY,compY,sp = 15,//可调整时间间隔,步进值不宜过大,不然IE下有点闪屏:timeGap = 5,doc = document.documentElement,docBody = document.body;// 调整初始位置compY = initY = 150;roll.style.right = initX + "px";; (function () {var curScrollTop = (doc.scrollTop || docBody.scrollTop || 0) - (doc.clientTop || docBody.clientTop || 0);//每次comP的值都不一样;直到ro11.style.top===doc.scrollToptinitY;compY += (curScrollTop + initY - compY) / sp;roll.style.top = Math.ceil(compY) + "px";setTimeout(arguments.callee, timeGap);})();