2016-12-27 189 views
0

使用math.random,我可以随机将div放置在左边。但我需要随机设置“左”和“右”位置。随机css位置jquery

jQuery('#popup-container').css({'left' : (Math.floor(Math.random() * 15) + 3) + '%'})
<div id="popup-container" style="background:red;width:30px; height:30px;"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

实施例,在属性 “的CSS({左”,与 “左或右” 的randon。与这些位置的数组。我如何做呢?

回答

3

简单地使一个数组,推动“左”和“右”了进去。

var positions = []; 
positions.push('left'); 
positions.push('right'); 

现在,使用的Math.random选择的职位数组的索引。

jQuery('#popup-container').css(positions[Math.floor(Math.floor(Math.random()%2))], (Math.floor(Math.random() * 15) + 3) + '%') 

希望这会有所帮助。

问候

+0

谢谢SPIDS:d 但代码是给语法错误,难道我错了吗? –

+1

不,也许我写了一个错误的语法:D 给我一分钟,我没有测试过。我会测试它并进行编辑;) –

+1

进行了必要的更改。请现在审查 –