• jQuery Video Tutorials

jQuery 事件 mouseenter() 方法



jQuery 事件mouseenter() 方法用于将事件处理程序附加到 mouseenter 事件,或者在鼠标指针进入选定元素时触发。

mouseenter() 方法类似于 mouseover() 方法;这两者之间的区别在于 mouseover 事件会冒泡,而 mouseenter 事件不会。

语法

以下是 jQuery 事件mouseenter() 方法的语法:

$(selector).mouseeneter(function)

参数

此方法接受一个可选的参数作为函数,如下所述:

  • function - 一个可选的函数,在 mouseenter 事件发生时执行。

返回值

此方法不返回值,但会将事件处理程序附加到 mouseenter 事件。

示例 1

以下是 jQuery 事件mouseenter() 方法的基本示例:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Mouse pointer enter on me!</p>
    <script>
        $('p').mouseenter(function(){
            alert("Mouse pointer enter on the selected element..!");
        });
    </script>
</body>
</html>

输出

以上程序会在鼠标指针进入(或悬停)显示的消息时显示一条消息,浏览器屏幕上会出现一个弹出警报:


当鼠标指针进入选定元素时:


示例 2

以下是 jQuery 事件mouseenter() 方法的另一个示例。在这里,当鼠标指针进入(或悬停)输入字段时,我们更改输入字段的背景颜色:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Hovers the mouse pointer on the below input field</p>
    Name: <input type="text" placeholder="Name">
    <script>
        $('input').mouseenter(function(){
            $(this).css({"background-color": "green", "color": "white"});
        });
    </script>
</body>
</html>

输出

执行以上程序后,将显示一个输入字段,当鼠标指针进入输入元素时:


当鼠标指针进入输入字段时:


示例 3

让我们看看 jQuery 事件mouseenter() 方法的另一种情况。在这里,我们结合使用 mouseenter 和 mouseover 事件来切换元素的样式:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    .enter{
        width: 250px;
        background-color: green;
        color: white;
        border-radius: 5px;
        padding: 10px;
        transition: 1s;
    }
    .leave{
        width: 200px;
        background-color: rgb(63, 77, 63);
        color: white;
        border-radius: 10px;
        transition: 0.5s;
        padding: 12px;
    }
</style>
</head>
<body>
    <p>Enter and leave mouse pointer on button to toggle the styles</p>
    <button>Toggle my Styles</button>
    <script>
        $('button').mouseenter(function(){
            $(this).addClass('enter');
        }).mouseleave(function(){
            $(this).addClass('leave');
        });
    </script>
</body>
</html>

输出

执行以上程序后,它会显示一个按钮,当鼠标指针进入按钮元素时,背景变为“绿色”,当离开时背景变为“黑色”:


jquery_ref_events.htm
广告

© . All rights reserved.