Html <div> 中的 JavaScript 函数 onhover

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15486376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:38:35  来源:igfitidea点击:

JavaScript function onhover in <div>

javascripthtml

提问by Kyrbi

I have got this code in HTML:

我在 HTML 中有这个代码:

<div id="choice" onHover="npcRoll()">
    <p>Choose your weapon!</p>
    <button id="rock" onClick="choose(1)">Rock</button>
    <button id="paper" onClick="choose(2)">Paper</button>
    <button id="scissors" onClick="choose(3)">Scissors</button>
    <p>You chose <span id="userChoice"></span>!</p>
</div>

And here is my JavaScript code for it:

这是我的 JavaScript 代码:

// Random
var random = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};  

// NPC
var npc;
function npcRoll(){
    npc = random(1, 3);
}

And here is the CSS code:

这是 CSS 代码:

#choice {
    margin: 0 auto;
    border: 2px solid gray;
    width: 350px;
}

The idea was to make roll NPC number every time the user hovers over the <div>but it doesn't work. Can you help me with it?

这个想法是每次用户将鼠标悬停在 上时滚动 NPC 编号,<div>但它不起作用。你能帮我解决吗?

回答by VisioN

There is no onHoverevent, use onmouseover:

没有onHover事件,使用onmouseover

<div id="choice" onmouseover="npcRoll()">

回答by HymanDan9

If PC, There is no onHoverevent, just use onmouseover.

如果PC,没有onHover事件,只需使用onmouseover

But in mobile, There are some hoverevent. for example:

但是在移动端,有一些hover事件。例如:

public class HoverDemoActivity extends Activity {  
    private Button btnBottom;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        btnBottom = (Button) findViewById(R.id.btn_bottom);  
        btnBottom.setOnHoverListener(new OnHoverListener() {  
            @Override  
            public boolean onHover(View v, MotionEvent event) {  
                int what = event.getAction();  
                switch(what){  
                 case MotionEvent.ACTION_HOVER_ENTER:  //鼠标进入view  
                     System.out.println("bottom ACTION_HOVER_ENTER");  
                     break;  
                 case MotionEvent.ACTION_HOVER_MOVE:  //鼠标在view上  
                     System.out.println("bottom ACTION_HOVER_MOVE");  
                     break;  
                 case MotionEvent.ACTION_HOVER_EXIT:  //鼠标离开view  
                     System.out.println("bottom ACTION_HOVER_EXIT");  
                     break;  
                }  
                return false;  
            }  
        });  
    }  
}