[英]Making div position change with button using JS
單擊該按鈕時,我試圖移動div的位置,但是它不起作用。 這是我的代碼:
<script>
function changePosition1() {
document.getElementsByTagName("div").style.top="300px";
}
</script>
<button type="button" onclick="changePosition1()">click me</button>
<div style="position: absolute; height:100px; width:100px; background-color: green;"></div>
更好的方法是將id =“ mydiv”添加到div並使用document.getElementById(“ mydiv”)對其進行引用。
因為document.getElementsByTagName("div")
返回的是元素集合,而不是單個元素。
編輯:使用document.getElementsByTagName("div")[0]
getElementsByTagName返回一個數組。 嘗試數組的第一個元素
document.getElementsByTagName("div")[0].style.top="300px
getElementsByTagName方法返回一個數組,因此您需要指定該數組的第一個元素:
<script>
function changePosition1()
{
document.getElementsByTagName("div")[0].style.top="300px";
}
</script>
<button type="button" onclick="changePosition1()">click me</button>
<div style="position: absolute; height:100px; width:100px; background-color: green;"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.