只想生成一个随机数,然后将其作为类添加到现有的 div 中。
但是无法让addClass识别该变量。
JS
$(function() {
$("#button_text").mouseenter(function() {
var randomNum = Math.Round(Math.random()*3);
$("#buttons").addClass(randomNum);
}).mouseleave(function() {
$("#buttons").removeClass(randomNum)
});
});
HTML
<div id="buttons">
</div>
非常感谢任何帮助。
<小时/>感谢您的帮助。
最终解决方案是...
JS
$(function() {
$("#button_text").mouseenter(function() {
randomNum = 'rand' + Math.round(Math.random()*2);
$("#buttons").addClass(randomNum);
}).mouseleave(function() {
$("#buttons").removeClass(randomNum)
});
});
HTML
<div id="buttons">
</div>
<p>Insert intro sentence here.</p>
<div id="button_text">
<p>Insert text here that will display the random button background when moused over</p>
</div>
CSS
#button_text
{
display: block;
}
#buttons
{
width: 200px;
height: 200px;
display: block;
position: absolute;
top: 145px;
left: 370px;
z-index: -999;
}
#buttons.rand0
{
background: url(/hover_buttons.png) no-repeat;
background-position: 0 0;
}
#buttons.rand1
{
background: url(/hover_buttons.png) no-repeat;
background-position: 0 -230px;
}
#buttons.rand2
{
background: url(/hover_buttons.png) no-repeat;
background-position: 0 -440px;
}
最佳答案
这里有几个问题。
范围 - 调用 mouseout 方法时,变量 randomNum 不存在,因此仅添加您的类。
即使您将其设置为全局变量,如果您多次使用此代码,也无法解决您的问题(情况可能并非如此,因为您似乎正在使用 ID,但以防万一。 )
它是
Math.round
而不是Math.Round
类不应仅由数字组成
我使用 jQuery 数据 api 来存储随机类名,以便您稍后可以检索它。这是您想要实现的目标的 fiddle :http://jsfiddle.net/jomanlk/339c5/
$("#button_text").mouseenter(function() {
var randClass = 'randomClass' + Math.round(Math.random() * 3);
$("#buttons").addClass(randClass);
$("#buttons").data('randClassValue', randClass);
}).mouseleave(function() {
var randClass = $("#buttons").data('randClassValue');
$("#buttons").removeClass(randClass)
});
<p id='button_text'>
<a id='buttons'>Buttons</a>
</p>
关于jquery - 将随机变量传递给 addClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6502705/