gpt4 book ai didi

javascript - 使用JS在页面周围移动一个div

转载 作者:太空宇宙 更新时间:2023-11-04 05:25:15 25 4
gpt4 key购买 nike

全部,

这里完全是新手,但有人可以检查这段代码并让我知道我哪里出错了吗?

我想要达到什么效果:我在网页上有大约 9 个 div,由图像和文本组成,当用户将鼠标悬停在 div 内的图像上时,文本会成为焦点。我希望这些 div“看起来”在页面周围 float 。

所以我做了什么:我在网页上使用 CSS 完全定位了 div。现在我正在使用 JS 将 div 从它们的位置移动到页面上的设置位置(将为每个 div 执行此操作)并尝试为 div 提供随机移动的效果。这是代码:

        <script language="javascript">
var x = document.getElementById("cr001").style.left;
var y = document.getElementById("cr001").style.top;
var d_x = 75;
var d_y = 100;
var interval = 2; //move by only 2px...

function moveImage() {
if(x < d_x) x = x + interval;
if(y < d_y) y = y + interval - 1; //move y by only 1px

document.getElementById("cr001").style.left = x+'px';
document.getElementById("cr001").style.top = y+'px';

if ((x + interval < d_x) && (y + interval < d_y)) {
window.setTimeout('moveImage()',100);
}
}
</script>
</head>

<body onload="moveImage()">
<div id="blackhole"><img src="img/bimg.png" alt="blackhole" /></div>
<div id="container">

<div id="cr001" class="twinkles">
<a href="#">
<img src="img/cr.png" alt="Co is about your freedom" />
<span>Co is about your freedom</span></a>

</div>

</body>

谁能解释一下我哪里出错了?

干杯,

最佳答案

根据精简后的帖子,我现在看到您正在尝试使用 var x = document.getElementById("cr001").style.left; 访问头部的正文内容;

这是行不通的,因为当头部被加载时, body 还没有准备好。你应该创建一个如下所示的 init() 函数:

function init(){
window.x = document.getElementById("cr001").style.left;
window.y = document.getElementById("cr001").style.top;
moveImage();
}

然后将其附加到主体上。

编辑:好的,这里有一些修改后的代码可以满足您的需求。您可以将其保存在名为 index.html 的文件中并在 Firefox 中启动它。我为你分解了它:

<html>
<head>
<script language="javascript">
var d_x = 75;
var d_y = 100;
var interval = 2;

//init is used for getting things up and running once the page is loaded
function init(){
//optimization: only get the element once
var el = document.getElementById("cr001")
x = parseInt(el.style.left);
if(isNaN(x)){
//parseInt("") == NaN
x = 0;
}
y = parseInt(el.style.top);
if(isNaN(y)){
//ditto
y = 0;
}
//call the nuts of this script
moveImage();
}

//this is mostly unchanged
function moveImage() {
if(x < d_x){
x = x + interval;
}else{
//lets keep looping just for fun!
x = 0;
}
if(y < d_y){
y = y + interval - 1; //move y by only 1px
}else{
y = 0;
}

//optimization: only get the element once
var el = document.getElementById("cr001")
el.style.left = x + 'px'; //dont forget to add 'px' back in
el.style.top = y + 'px';

//loop, don't use strings in setTimeout since this is basically eval...eval is evil
setTimeout(moveImage, 100);

}
</script>
</head>
<body onload="init()">
<div id="container">
<!-- IMPORTANT: POSITION IS ABSOLUTE -->
<div id="cr001" style="position:absolute; width:10px; height:10px; background-color:black"></div>
</div>
</body>

关于javascript - 使用JS在页面周围移动一个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5252864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com