如何在Javascript中设置负边距?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (47)
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;
}
提问于
用户回答回答于

这样操作:

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');

扫码关注云+社区

领取腾讯云代金券