【问题标题】:how to change image position using javascript?how to get div width in integer?如何使用 javascript 更改图像位置?如何以整数形式获取 div 宽度?
【发布时间】:2018-08-31 09:16:55
【问题描述】:

对不起,如果它太愚蠢了。 我想用纯 JavaScript 自己制作一个图像滑块。所以我使用了以下代码。我是 javascript 的初学者

<div class="w3-div" id="img-div" style="width:100%; height: 480px; border: 4px solid black;">
  <!-- i'm not making image position absolute because if i make it absolute it is not fitting in the div morever the fixed header is not working--->
<img src="assets/pics/1.jpg" id="header" class="w3-image" style="width: 100%; height:473px; padding-bottom: 0px;">
</div>
<script type="text/javascript">
  window.onload = function() {

    setInterval(changepic, 10000);
  }

  function changepic() {

    //alert("changing pic ");
    var p = document.getElementById('header');
    p.style.position = "absolute";
    //i know that style.width returns string but what else i can do?
    //loop to slide out the img from div
    for (var i = 0; i <= document.getElementById('img-div').style.width; i++) {
      p.style.left = i + "px";
      //p.style.right= i+"px";
    }
     // loop to slide in the image in div
    for (var i = document.getElementById('img-div').style.width; i >= 0; i--) {
      //p.style.left = i+"px";
      p.style.right = i + "px";
    }
    //put random image over here or just relocate the first image
    p.style.position = "relative";
    p.style.left = "0px";



  }
</script>
在此先感谢,请帮助我。 网站链接是here.(http://yirusworld.000webhostweb.com)

【问题讨论】:

标签: javascript html css image dom


【解决方案1】:

我不太明白你的问题,但有些地方我认为这会使行为出错。你可以举一些你在做什么的例子,然后我可以提供更好的帮助。

  • 您正在使用

document.getElementById('img-div').style.width

  • 它返回 100% - 正是您在元素中设置的值。如果要获取该元素的实际宽度,则应改为使用 offsetWidth。

var width = document.getElementById('img-div').offsetWidth;

  • 对于你的循环,因为img-div是不变的,你应该让它的宽度为一个变量——这里是宽度——那么在循环过程中,js就不用取img-div的宽度了每次运行时,它只使用可变宽度,从而获得更好的性能。

  • 如果您希望 p 的位置是绝对的,请添加 position: relative to its parent

【讨论】:

    猜你喜欢
    • 2013-09-18
    • 2014-07-06
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多