【问题标题】:Using Javascript to move elements positioned using CSS Top Bottom Left Right使用 Javascript 移动使用 CSS 上左下右定位的元素
【发布时间】:2011-08-17 22:28:21
【问题描述】:

我有一个没有任何设定尺寸的容器。我希望容器的大小由其内容驱动。像这样:

    #containerTL{
    position:absolute;
    bottom: 0px;
    right: 0px;
    margin: 5px;
    border: 1px solid black;
    cursor: default;    
    }

    #content{
    position:relative;
    background: gray;
    margin: 0px;
    top: 0px;
    height: 100px;
    width: 120px;
    cursor: default;    
    }

    <div id="containerTL"><div id="content"></div></div>

我还想移动容器的位置,让它的内容随行随行。通过修改容器 style.top 和 style.left 来设置位置很容易,我遇到的问题是元素可能使用“bottom”或“right”定位。如果没有设置尺寸,当我设置 top 和 left 属性时,容器会增长,而不是移动。

我想我理解这个问题。假设样式指定了底部和左侧位置,我使用 javascript 更新顶部和左侧属性,设置了顶部和左侧属性,但样式指定了底部属性。

我想一旦我更新了 top 和 left,我总是可以将 bottom 和 right 属性设置为“auto”......但是如果我希望能够将每个元素发送回它的原始位置,一般来说,而不写每个元素的特殊情况。

这里有一个小提琴来说明这个问题:fiddle

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    你可以这样做:

    this.style.right = '';
    this.style.left = '';
    this.style.top = '';
    this.style.bottom = '';
    

    它会取消您通过.style 设置的任何内容并恢复为您在样式表中定义的内容。

    请参阅此fiddle 以获取示例。单击一次移动它,再次单击应将其移回原始位置。

    【讨论】:

      【解决方案2】:

      Demo

      另外两侧需要如下代码

      this.style.bottom = "auto";
      this.style.right = "auto";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 2022-11-20
        • 1970-01-01
        相关资源
        最近更新 更多