首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我如何能够在javascript中随机设置图像的位置?

我如何能够在javascript中随机设置图像的位置?
EN

Stack Overflow用户
提问于 2015-12-17 03:57:04
回答 3查看 1.4K关注 0票数 0

我试图使smile.png图像出现在特定<div>中的一个随机位置。

我所做的就是设置variable.style.top= top_position+'px' & variable.style.left = left_position+"px"

然而,到目前为止,我得到的是水平对齐的图像,而不是随机定位的。我怎么能这么做?

代码语言:javascript
运行
复制
var theLeftSide = document.getElementById("leftSide");
var randomY = Math.round(Math.random()) + 'px';
var randomX = Math.round(Math.random()) + 'px';

function generateFaces() {
  for (numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
    createElement(numberOfFaces);
  }
}

number = 0;

function createElement() {
  number++;
  //creating the image on the leftside
  var smiley = document.createElement('img');
  smiley.src = "smile.png";
  smiley.style.position = "absolute";
  smiley.style.left = randomX;
  smiley.style.top = randomY;
  theLeftSide.appendChild(smiley);
}
代码语言:javascript
运行
复制
 #leftSide {
   position: absolute;
   width: 500px;
   height: 500px;
 }
 #rightSide {
   position: absolute;
   width: 500px;
   height: 500px;
   left: 500px;
   border-left: 1px solid black;
 }
代码语言:javascript
运行
复制
<body id="smileyGuessingGame" onload="generateFaces()">
  <h1>Matching Game</h1>
  <p>Click on the extra smiling face on the left</p>
  <div id="leftSide">
  </div>
  <div id="rightSide">
  </div>


</body>

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-12-17 04:30:01

代码中很少有语法错误。您可以将代码与下面提供的代码进行比较。

还请注意,toFixed返回一个numObj的字符串表示形式,它不使用指数表示法,并且在小数位之后有确切的数字。

试试这个:

代码语言:javascript
运行
复制
var theLeftSide = document.getElementById("leftSide"),
  top_position = parseInt(Math.random() * ($(document).width() - 500)),
  left_position = parseInt(Math.random() * ($(document).width() - 500));

function generateFaces() {
  for (var numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
    createElement(numberOfFaces);
  }
}

var number = 0;

function createElement() {
  number++;
  //creating the image on the leftside
  var smiley = document.createElement('img');
  smiley.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Smiley_head_happy.svg/2000px-Smiley_head_happy.svg.png";
  smiley.style.position = 'absolute';
  smiley.style.top = top_position + "px";
  smiley.style.left = left_position + "px";
  theLeftSide.appendChild(smiley);
  top_position += 20;
  left_position += 20;
}
代码语言:javascript
运行
复制
 #leftSide {
   position: absolute;
   width: 500px;
   height: 500px;
 }
 #rightSide {
   position: absolute;
   width: 500px;
   height: 500px;
   left: 500px;
   border-left: 1px solid black;
 }
 img {
   width: 100px;
   height: 100px;
 }
代码语言:javascript
运行
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body id="smileyGuessingGame" onload="generateFaces()">
  <h1>Matching Game</h1>
  <p>Click on the extra smiling face on the left</p>
  <div id="leftSide">
  </div>
  <div id="rightSide">
  </div>
</body>

Fiddle here

票数 1
EN

Stack Overflow用户

发布于 2015-12-17 07:02:47

我会用jQuery和对此进行编码。这里有个小摆设:

https://jsfiddle.net/mckinleymedia/3z6wsnyf/2/

html:

代码语言:javascript
运行
复制
<h1>Matching Game</h1>
<p>Find the unique image</p>
<div class="game"></div>

守则如下:

代码语言:javascript
运行
复制
var game = function(options) {
  var panes = 2,
    game = $('.game'),
    height = 500,
    width = game.width() / panes - 20,
    itemSize = 50,
    faces = 5,
    guesses = 5,
    setupBoard = function() {
      game
        .empty();
      _.times(panes, function(p) {
        game
          .append(
            $('<div>')
            .addClass('pane pane' + p)
            .css('height', height + 'px')
            .css('width', width + 'px')
          );
      })
    },
    startGame = function() {
      _.times(faces, function(i) {
        _.times(panes, function(p) {
          $('.pane' + p)
            .append(
              $('<img>')
              .attr('src', 'http://lorempixel.com/200/20' + i)
              .addClass('img-' + i)
              .css('top', _.random(height - itemSize) + 'px')
              .css('left', _.random(width - itemSize) + 'px')
            );
        })
      });
      $('.game img').click(function() {
        guesses--;
        alert('Nope!  You\'ve got ' + guesses + ' guesses remaining.');
      });
      $('.pane' + _.random(panes - 1))
        .append(
          $('<img>')
          .attr('src', 'http://lorempixel.com/200/20'+ (faces + 1))
          .addClass('img-t')
          .css('top', _.random(height - itemSize) + 'px')
          .css('left', _.random(width - itemSize) + 'px')
          .click(function() {
            alert('You got it! Good job!  You just cleared ' + faces + ' images!  You\'ve got ' + guesses + ' guesses remaining.');
            faces++;
            setupBoard();
            startGame();
          })
        );
      $('.game img')
        .css('height', itemSize + 'px')
        .css('width', itemSize + 'px')
        .css('-moz-border-radius', itemSize / 2 + 'px')
        .css('-webkit-border-radius', itemSize / 2 + 'px')
        .css('border-radius', itemSize / 2 + 'px')
        .css('-khtml-border-radius', itemSize / 2 + 'px')

    };
  setupBoard();
  startGame();
};
game();
票数 1
EN

Stack Overflow用户

发布于 2015-12-17 04:29:11

也许像这样的东西能起作用:

代码语言:javascript
运行
复制
   function generateRandom(min, max) {
      var num = Math.random() * (max - min) + min;
      return Math.floor(num);
    }

    var width,
        height, 
        img;
    width = $( '#leftSide' ).width();
    height = $( '#leftSide' ).height();
    img = $('<img id="smiley">'); 
    img.attr('src', 'http://vignette2.wikia.nocookie.net/robocraft/images/2/26/Smile.png');
    img.css('top',generateRandom(0,height));
    img.css('left',generateRandom(0,width));
    img.appendTo('#leftSide');

演示:http://codepen.io/anon/pen/PZZrzz

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34326357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档