我正在使用JavaScript渲染绝对定位的p元素,但无法弄清楚如何使其与上面的图像对齐

时间:2019-10-31 01:07:31

标签: javascript vue.js vuejs2

我试图实现以下目标-每当我将鼠标悬停在图像元素上时,我都想在悬停的图像下方渲染p元素,并以编程方式设置其top和left属性,以使其与上方的图像完全对齐。我已经完成了大部分操作,但是,我不知道如何对图像进行垂直对齐。我当前的代码结果如下:

enter image description here

这是因为我将left属性设置为等于this.eOffsetLeft = e.target.offsetLeft + width/2,即图像的offsetLeft及其宽度/ 2,这使我的测试p元素在图像中间之后开始。我想要的或多或少是这样的:

enter image description here

这是可以轻松实现的吗?感谢您的阅读!

我的模板中包含以下HTML:

 <section class='skills'>
     <img @mouseover='displayAlt' @mouseleave='hover = false' src="#">
     <p v-if='hover' v-bind:style='{ "position": "absolute", "top": eOffsetTop + "px", "left": eOffsetLeft + "px" }'>Test</p>
 </section>

然后在我的脚本标签中添加以下JS:

<script>
    export default {
        data(){
            return {
                hover: true,
                eOffsetTop: null,
                eOffsetLeft: null
            }
        },
        methods: {
            displayAlt(e){
                this.hover = true;
                console.log(e)
                this.eOffsetTop = e.target.offsetTop + e.target.height + 40
                let width = e.target.width
                this.eOffsetLeft = e.target.offsetLeft + width/2

            }
        }
    }
</script>

2 个答案:

答案 0 :(得分:1)

不幸的是,我对vue.js不熟悉。

但是,使用香草html,javascript和css,您可以做到这一点(请参见代码段)。

在CSS中,您需要将父元素的position设置为relative。然后在p中设置position: absolute;。这使您可以将元素放置在父级中。

然后使用mouseover标签内的mouseoutimg事件,可以将p标签放置在所需的位置。将p的宽度设置为图像的宽度,并在需要的地方设置顶部。由于text-align设置为center,因此文本将自动与中间对齐。

function showP(x) {
  let p = document.querySelector("section.skills > p");
  p.style.display = 'block';
  p.style.width = x.width + 'px';
  p.style.top = x.height - 42 + 'px';
}

function hideP(x) {
  let p = document.querySelector("section.skills > p");
  p.style.display = 'none';
}
section {
  position: relative;
}

section.skills p {
  display: none;
  position: absolute;
  text-align: center;
}
<html>

<body>
  <section class='skills'>
    <img onmouseover="showP(this)" onmouseout="hideP(this)" src="https://www.w3.org/html/logo/img/html5-topper.png" height="200">
    <p>Test</p>
  </section>
</body>

</html>

答案 1 :(得分:1)

在没有JavaScript的情况下调整@Steve的答案。改用CSS和:hover

section.skills {
  width: 300px;
  position: relative;
}

section.skills img {
  width: 100%;
}

section.skills p {
  display: none;
  position: absolute;
  text-align: center;
  bottom: 0;
  width: 100%;
}

section.skills:hover p {
  display: block;
}
<html>

<body>
  <section class='skills'>
    <img src="https://www.w3.org/html/logo/img/html5-topper.png">
    <p>Test</p>
  </section>
</body>

</html>