gpt4 book ai didi

javascript - 键盘事件 :Moving div to left with margin-left on pressing key

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:00 26 4
gpt4 key购买 nike

我想在按下左键盘箭头时向左移动一个 div。

function arrowright (event){
var vaiss= document.getElementById("vaisseau");
var size= vaiss.style.marginLeft;
alert(size); //here I get empty message
if (event.which==39)
vaiss.style.marginLeft=size+"5px";
alert (vaiss.style.marginLeft); // here I get 5px not previous left margin + 5px
}

这里是 CSS:

#vaisseau{
bottom:0;
position:absolute;
margin-left:300px;
display;block;
}

和 HTML:

div id="vaisseau" class="elements"><img src="vaisseau.jpg"></div>

我认为问题是它没有读取 margin-left 的实际值。

编辑:css 样式在外部文件中

最佳答案

在这里找到答案:How to get margin value of a div in plain JavaScript?

T.J.克劳德说:

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

例子:

var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

总结:

document.getElementById("vaisseau").style.marginLeft仅当 HTML 代码如下所示时有效:<div id="vaisseau" class="elements" style="margin-left: 300px"></div>

关于javascript - 键盘事件 :Moving div to left with margin-left on pressing key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37749905/

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