编程网站中的随机图像位置?

时间:2016-02-24 14:10:12

标签: html css image random marquee

我想做到这一点,所以我有"敌人"在随机高度的特定网页的背景中产生(不是背景,只是它上面的图像)并在屏幕上滚动。现在我有类似的东西:

<script>
    function numberRandomizer(){
      var x = Math.floor((Math.random() * 500) + 300); //random number between 300 and 800
      return x;
    }
  </script>

我尝试了两种方法将此随机变量X应用于通过在屏幕上滚动循环的图像:

1)做我认为可行的工作并编辑每个图像以获得顶部和左侧的随机值

  <marquee behavior="scroll" direction="left" scrollamount="numberRandomizer()"><img src="/aboutme/enemy.png" width="120" height="80" top="numberRandomizer()" left="numberRandomizer()"/><p></marquee>

2)尽管据我所知它会使所有敌人都具有相同的位置,但尝试使用CSS样式来使位置随机,以确定它是否有效:

 <style>
    img {
      top: numberRandomizer();
      left: numberRandomizer();
    }
  </style>

这两种风格都不能为图像位置设置一个随机值,我是否会犯一个小错误或完全错误的方式?

作为一个额外的问题:是否可以设置选框以使每个图像随机方向?

2 个答案:

答案 0 :(得分:1)

你也可以使用普通的javascript做同样的事情

HTML:

<marquee behavior="scroll" direction="left" id="elem">Test</marquee>
<br/>
<button id="butR">Right</button>
<button id="butL">Left</button>

<div class="area">
<div id="enemy"></div>
</div>

JS:

document.getElementById('butR').addEventListener("click", function(){
    document.getElementById('elem').setAttribute("direction", "right");   
});

document.getElementById('butL').addEventListener("click", function(){
    document.getElementById('elem').setAttribute("direction", "left");   
});

function numberRandomizer(){
  var x = Math.floor((Math.random() * 250) + 50); //random number between 50 and 300
  return x;
}


document.getElementById('enemy').style.top = numberRandomizer() + 'px';
document.getElementById('enemy').style.left = numberRandomizer() + 'px';

我还添加了改变品牌方向的方法。看看这个小提琴:

https://jsfiddle.net/oyv324z9/

答案 1 :(得分:0)

正如一对夫妇所说,你不能混合使用JS和CSS。如果你使用jQuery,这很简单。基本上,您希望使用jQuery将CSS样式添加到img。这样的事情。

//your trigger here and then..
$( "#your_img_id" ).css( "left", function(index) {
  return index * numberRandomizer() ;
});
$( "#your_img_id" ).css( "right", function(index) {
  return index * numberRandomizer() ;
});