使用 math.random,我可以将 div 随机定位到左侧。但我需要随机设置“左”和“右”位置。
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({left”中,有一个带有“left or right”的随机数。具有这些位置的数组。我该怎么做?
最佳答案
只需创建一个数组并将“左”和“右”压入其中即可。
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) + '%')
希望这对您有所帮助。
问候
关于javascript - 随机CSS位置jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341242/