NSLCJ_wzqdnzqst
2021-03-02 17:25
采纳率: 100%
浏览 39
已结题

div盒子的属性,没有因为事件改变

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box1 {
				position: absolute;
				left: 100px;
				top: 100px;
			}

			img {
				width: 300px;
			}

			#btn01 {
				position: absolute;
				right: 0;
			}
		</style>

		<script type="text/javascript">
			window.onload = function() {
				var box1 = document.getElementById("box1");

				var left = 0;

				var top = 0;

				if (window.getComputedStyle) {
					left = getComputedStyle(box1, null).left;
					top = getComputedStyle(box1, null).top;
				} else {
					left = box1.currentStyle.left;
					top = box1.currentStyle.top;
				}

				document.onscroll = function() {
					// box1.style.top = (document.body.scrollTop || document.documentElement.scrollTop)+"px";
					// box1.style.left = (document.body.scrollLeft || document.documentElement.scrollLeft)+"px";
					// var left=0;
					// if(window.getComputedStyle){
					// 	left = getComputedStyle(box1,null).left;
					// }else{
					// 	left = box1.currentStyle.left;
					// }
					// alert(left);


					var st = document.body.scrollTop || document.documentElement.scrollTop;
					var sl = document.body.scrollLeft || document.documentElement.scrollLeft;

					box1.style.left = parseInt(sl)+parseInt(left) +"px";
					box1.style.top = parseInt(st) + parseInt(top) + "px";
				}
			}
		</script>
	</head>
	<body style="height: 2600px; width: 3000px;">
		<div id="box1">
			<button id="btn01">×</button>
			<img src="../image/2.jpg" />
		</div>
	</body>
</html>
  • 收藏

3条回答 默认 最新

  • SnailsH 2021-03-02 17:34
    已采纳

    box1.style.left = 200 + "px";

    已采纳该答案
    1 打赏 评论
  • 天际的海浪 2021-03-02 17:37

                    window.onscroll = function() {
     
                        var st = document.body.scrollTop || document.documentElement.scrollTop;
                        var sl = document.body.scrollLeft || document.documentElement.scrollLeft;
     
                        box1.style.left = 200 + "px";
                        box1.style.top = st + parseFloat(top) + "px";
                    }
     

    1 打赏 评论
  • 封印di恶魔 2021-03-02 17:37

    首先   script放到html下面     在方法里加个console.log输出left和top看看   

    如果有值可能就你加的滚动的问题,看看滚动有没有触发

    另外可以先写固定值把效果实现再改成动态的

    1 打赏 评论

相关推荐 更多相似问题