Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按类选择元素,然后移动它_Javascript_Html - Fatal编程技术网

Javascript 按类选择元素,然后移动它

Javascript 按类选择元素,然后移动它,javascript,html,Javascript,Html,我需要根据它的类名选择某个div 选择后,我需要将其向上移动100像素 以下是我到目前为止所做的尝试: HTML <div style="z-index:101; position: absolute; left: 0px; top: 300px; width: 20px; height:450px; padding: 0px; border: 0px;" class="wrapper" >Content</div> 不确定我是否正确理解节点列表 1.您在getE

我需要根据它的类名选择某个div

选择后,我需要将其向上移动100像素

以下是我到目前为止所做的尝试:

HTML

<div  style="z-index:101;  position: absolute; 
left: 0px; top: 300px; width: 20px; height:450px;
padding: 0px; border: 0px;" class="wrapper" >Content</div>
不确定我是否正确理解节点列表


1.您在
getElementsByClassName()
中缺少一个
s

2。您使用了
class
作为变量名,但它是一个保留字。就说别的吧

3.要向上移动,请更改
.style.top
属性(300-100=200px)

固定代码:

var wrapper=document.getElementsByClassName(“wrapper”);
var div=wrapper[0];
div.style.top='200px'
内容
为什么不起作用? 令牌类是保留的,不能用作变量名。 其次,您在getElementsByCassName()中输入了一个错误

解决方案 我们可以改为使用document.querySelector()并省略数组,因为它总是提供第一个匹配项,这在您的情况下是有效的

document.querySelector('.wrapper').style.top = '100px';
要将其从初始位置向上移动100px,请使用

var tE = document.querySelector('.wrapper');
tE.style.top = Math.max(parseInt(tE.style.top) - 100, 0).toString() + 'px';

谢谢工作得很好。
var tE = document.querySelector('.wrapper');
tE.style.top = Math.max(parseInt(tE.style.top) - 100, 0).toString() + 'px';