【问题标题】:I want to click a button and have a random image appear in a random location within my Container我想单击一个按钮并在我的容器内的随机位置出现一个随机图像
【发布时间】:2018-03-08 23:51:06
【问题描述】:

我希望每次单击底部的“尝试”按钮时都能在随机位置出现随机图像。 我已经能够让它随机化图像,但我很难将随机位置也应用于随机化的图像。

<input id="input" type="text" placeholder="Enter a background colour...">

<button>enter</button>

<div id="container">
    <img id="picture" src="img/img1.jpg">
</div>

<button onclick="randAll();" id = "randomButton">Try!</button>


<script>
    var bColour = document.getElementById("container");
    var button = document.querySelector("button");
    button.addEventListener("click", clickHandler, false);
    button.style.cursor = "pointer";

    function clickHandler()
    {
        var input = document.querySelector("#input");
        bColour.style.backgroundColor = input.value;
    }

    var pix = new Array("img/img1.jpg", "img/img2.jpg", "img/img3.jpg", "img/img4.jpg");

    function choosePic() {
        var randomNum = Math.floor(Math.random() * pix.length);
        document.getElementById("picture").src = pix[randomNum]

    }

    function randPos() {
        Math.floor(Math.random() * 700);


    }


</script>

【问题讨论】:

    标签: javascript html css random


    【解决方案1】:

    像这样应用一些 CSS:

    #picture {
      position: absolute;
    }
    
    #container {
      width: 750px;
      height: 100px;
    }
    

    然后:

    function randPos() {
      var x = Math.floor(Math.random() * 700);
      document.getElementById("picture").style.left = x + 'px';
    }
    

    根据需要调整我选择的具体宽度和高度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多