我是Javascript的新手,我正在为学习目的从头开始建立一个网站。我偶然发现了我认为是错误的地方。我试图在我的一个元素上设置负边距,但它不起作用。这是对我不起作用的一句话:
document.getElementById("wrapper").style.marginLeft="-250px";
如何使用JavaScript在我的元素上设置负边距?下面是我的html:
<div class="wrapper">
<div class="wrapper_inside">
<img src="images/profile.png">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#portfolio">Portfolio</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
</ul>
</div>
</div>
下面是我的CSS:
.wrapper {
height: 100%;
width: 250px;
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
color: white;
background-color: #565656;
text-align: center;
transition: 0.5s;
}
-好了,我的javascript中的问题在前面。我必须切换函数,而不是$element.style.marginLeft=='0px'
,我使用了$element.style.marginLeft=='0'
发布于 2016-08-20 23:56:28
getElementById()
。它确实做到了这一点。所以你需要提供一个已经存在的id,而不是一个类。如果要按类选择元素,请执行以下操作。只需使用getElementsByClass()
(将返回一个包含该类所有元素的对象。
document.getElementById("wrapper").style.marginLeft = "-250px";
.wrapper {
height: 100%;
width: 250px;
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
color: white;
background-color: #565656;
text-align: center;
transition: 0.5s;
}
.big-wrapper {
width: 250px;
margin: auto;
}
<div class="big-wrapper">
<div id="wrapper">
<div class="wrapper_inside">
<img src="images/profile.png">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#portfolio">Portfolio</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
</ul>
</div>
</div>
</div>
使用JavaScript选择HTML元素有三种基本方法:
// by id
document.getElementById('myId');
// by class considering your element is the first in DOM to use this class
document.getElementsByClassName('myClass')[0];
// by selector
document.querySelectorAll('.myClass')[0];
// or
document.querySelector('#myId');
https://stackoverflow.com/questions/39056001
复制相似问题