[英]Change text with math random
我正在尝试在Codepen上制作Magic 8 Ball,但不幸的是我无法显示任何文字。 目前,我正在使用Math Random获得我需要的所有不同答案,但是我对html和JavaScript的交互方式非常不清楚。 这是我到目前为止的内容:
HTML:
//JavaScript: var words = [ 'It is certain', 'It is decidedly so', 'Etc', ]; var getRandomWord = function () { return words[Math.floor(Math.random() * words.length)]; }; $(function() { $('.eball').mouseenter(function(){ $('.textbox').html(getRandomWord()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="eball"> <div class="triangle"></div> <div class="textbox"></div> </div> </div>
稍作更改,您的代码即可正常工作。 给您的.eball
类一个固定的高度。
问题是您的.eball
div以零内容开头,这导致div
完全崩溃。 由于没有要输入的“区域”,因此您将无法触发mouseenter
事件。 给您要以固定大小(特别是高度)触发mouseenter
的div
将解决此问题。 另一种解决方案是使用一些初始文本或
来启动div
所以它不是空的。
var words = [ 'It is certain', 'It is decidedly so', 'Etc', ]; var getRandomWord = function () { return words[Math.floor(Math.random() * words.length)]; }; $(function() { $('.eball').mouseenter(function(){ $('.textbox').html(getRandomWord()); }); });
.eball { color: white; text-align: center; background-color: grey; height: 50px; width: 120px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="eball"> <p class="textbox"></p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.