点按钮完成元素内容交换JavaScript盒子模型的共合完整的程序
以下是一个使用JavaScript实现元素内容交换的完整程序:
<!DOCTYPE html>
<html>
<head>
<title>元素内容交换</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: lightblue;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}
.button {
margin-top: 10px;
}
</style>
</head>
<body>
<div id="box1" class="box">
Box 1
</div>
<div id="box2" class="box">
Box 2
</div>
<button class="button" onclick="swapContent()">点击交换内容</button>
<script>
function swapContent() {
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var temp = box1.innerHTML;
box1.innerHTML = box2.innerHTML;
box2.innerHTML = temp;
}
</script>
</body>
</html>
在上述程序中,我们创建了两个具有相同样式的盒子,并在每个盒子中放置了一些文本内容。接着我们创建了一个按钮,当点击按钮时会调用swapContent()函数。
swapContent()函数获取到box1和box2的元素对象,并使用一个临时变量来交换它们的innerHTML属性,从而实现了元素内容的交换。最后,我们将函数绑定到按钮的onclick事件上。
当点击按钮时,两个盒子的内容将会交换
原文地址: http://www.cveoy.top/t/topic/hWJg 著作权归作者所有。请勿转载和采集!