我有一个父div - myCcontainer,我有一个子div - div2。 当我移动父div时,子div应该占据相同的位置,父节点应该移动到某个地方。 我怎么能用JavaScript做到这一点?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.cpdiv{
background-color: yellow;
width:150px;
height:150px;
border: 2px solid black;
}
#myContainer {
width: 500px;
height: 500px;
position: relative;
border: 2px solid #222333;
}
#container {
width: 100%;
height:100%;
}
</style>
</head>
<body>
<div id="container" >
<div id="myContainer" >
<div >
<button id="btn3" onclick="myMove()">Move</button>
</div>
<div class="cpdiv" id="div2">
<label>hai</label>
</div>
</div>
</div>
<script>
function myMove() {
var elem = document.getElementById("myContainer");
document.getElementById("div2").style.position = "fixed";
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 150) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
稍微更改了你的CSS:
.cpdiv{
background-color: yellow;
width:150px;
height:150px;
border: 2px solid black;
top: 20px;
left:20px;
}