2016-11-29 53 views
0

我想在codepen上製作一個Magic 8球,但不幸的是我無法獲得任何文本出現。目前我正在使用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>

+0

似乎工作對我罰款:https://jsfiddle.net/qLk4nqdb/1/你導入jQuery的? – GAntoine

+2

'eball'沒有高度,所以'mouseenter'事件永遠不會發生。 – 2016-11-29 03:48:03

+0

至於torazaburo提到,你的代碼是好的,除非高度是問題 – Sreekanth

回答

2

您的代碼工作正常的微小變化。給你的.eball類固定的高度。

問題是您的.eball div從零內容開始,導致div完全崩潰。由於沒有「區域」進入,您將無法觸發mouseenter事件。給你div你想觸發mouseenter在一個固定的大小(特別是高度)將解決這個問題。另一種解決方案是用一些初始文本或&nbsp;開始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>