【问题标题】:Change DIV position to static section of DOM将 DIV 位置更改为 DOM 的静态部分
【发布时间】:2021-06-27 14:37:26
【问题描述】:

我有一个 vue 应用程序,我在其中创建了一些方法来将我的 div“工具箱”移动到 DOM 的不同部分。目前,DIV 加载在屏幕的右下角,它是静态的,如果我滚动页面,它不会移动。

我创建的方法试图实现相同的目标,但是将 DIV 移动到“左上角”、“右上角”、“左下角”,并且在找到要赋予的正确 px 值时遇到了一些问题给定的功能。有谁知道是否有更好的方法来做到这一点?

我的代码:

  <button @click="changePositionTopLeft">Move Top Left</button>
  <button @click="changePositionTopRight">Move Top Right</button>
  <button @click="changePositionBottomLeft">Move Bottom Left</button>


methods: {
changePositionTopLeft() {
  const divPosition = document.getElementById('sdk-ts-root')
  divPosition.style.left = '200px'
  divPosition.style.top = '200px'
},
changePositionTopRight() {
  const divPosition = document.getElementById('sdk-ts-root')
  divPosition.style.right = '400px'
  divPosition.style.top = '400px'
},
changePositionBottomLeft() {
  const divPosition = document.getElementById('sdk-ts-root')
  divPosition.style.left = '400px'
  divPosition.style.bottom = '400px'
}

} }

【问题讨论】:

    标签: javascript css vue.js position css-position


    【解决方案1】:

    当使用 Vue(或任何其他类似的库,如 React、Svelte 等)时,您不应直接与 DOM 交互,而应创建数据绑定来自动更新 HTML。

    这就是“Vue方式”应该如何做到的:

    let app = new Vue({
      el: '#app',
      data: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
    
      },
      computed: {
        style() {
          return `top: ${this.top}px; right: ${this.right}px; bottom: ${this.bottom}px; left: ${this.left}px;`
        }
      },
      methods: {
        changePositionTopLeft() {
          this.top = 200
          this.left = 200
        },
        changePositionTopRight() {
          this.top = 400
          this.right = 400
        },
        changePositionBottomLeft() {
          this.bottom = 400,
            this.left = 400
        },
        reset() {
          this.top = 0;
          this.right = 0;
          this.bottom = 0;
          this.left = 0;
        }
      }
    })
    #app {
      position: relative;
      height: 500px;
    }
    
    .el {
      position: absolute;
      
      /* some styling */
      height: 50px;
      width: 50px;
      background-color: red;
      color: white;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
        <div :style="style" class="el">DIV</div>
        <button @click="changePositionTopLeft">Move Top Left</button>
        <button @click="changePositionTopRight">Move Top Right</button>
        <button @click="changePositionBottomLeft">Move Bottom Left</button>
        <button @click="reset">Reset</button>
        top: {{top}} right: {{right}} top: {{bottom}} left: {{left}}
    </div>

    【讨论】:

    • 感谢您的反馈,您是对的,我应该为我的 vue 应用采用这种格式。 DIV 的定位仍然无法按预期工作。主要是我的问题是是否有默认值“px”将 div 设置为左​​上/右上或左下/右下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2014-04-20
    相关资源
    最近更新 更多