[英]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.