当鼠标进入二者的区域时触发fun1,离开时触发fun2。你也许会想到使用下面的方式
HomeWeb Front-endJS TutorialHover event solution for multiple elements in jQuery_jquery

1. Introduction to requirements

jQuery’s hover event is only for a single HTML element, for example:
Copy code The code is as follows:

$('#login').hover(fun2, fun2);

The fun1 function is called when the mouse enters the #login element , the fun2 function is called when leaving. This API can meet most needs.

However, sometimes we want fun1 to be triggered when the mouse enters two or more elements, and fun2 to be triggered when the mouse leaves them, while moving the mouse between these elements does not trigger any events. For example, two HTML elements are next to each other, as shown below:

Hover event solution for multiple elements in jQuery_jquery

Fun1 is triggered when the mouse enters the area between the two, and fun2 is triggered when the mouse leaves. You may think of using the following method
Copy code The code is as follows:

$('# trigger, #drop'),hover(fun1, fun2);

This method does not meet our needs, because fun2 and fun1 will be triggered when entering #drop from #trigger. To solve this problem, a relatively simple way is to change the HTML structure. The implementation is as follows:
Copy code The code is as follows:



< ;/div>


$('#container').hover(fun1, fun2);

This way by binding on the parent element hover event to achieve this function.

2. Example study

The picture below is a simplified diagram of a common drop-down menu. The HTML structure is as follows:

Hover event solution for multiple elements in jQuery_jquery
Copy code The code is as follows:

ul id="#nav">
  • < ;/li>


  • Drop-down menu

    • Dropdown item 1

    • Dropdown item 2

    • Dropdown item 3






  • The implemented JavaScript program is also very simple
    Copy code The code is as follows:

    $('#droplist').hover(function(){
    $( this).find('ul').show();
    }, function(){
    $(this).find('ul').hide();
    });

    This implementation method has clear logic, but it results in too many nested levels of HTML and a lot of inconvenience when writing CSS. For example:
    Copy code The code is as follows:

    #nav li { font-size:14px; }

    We want this CSS to set a 14-pixel font for the first-layer li element, but it also affects the second-layer element, so we have to use the following statement to rewrite it
    Copy code The code is as follows:

    #nav li li { font-size:12px; }

    3. Solution

    Change HTML structure
    Copy code The code is as follows:




    • Drop-down menu




    • Dropdown item 1

    • Dropdown item 2

    • Dropdown item 3



    Introduce JS files in sequence
    Copy the code The code is as follows:



    Control code
    Copy code The code is as follows:

    $.mixhover(
    '#trigger',
    '#drop',
    function(trg, drop){
    #(drop).show();
    },
    function(trg, drop){
    #(drop).hide();
    }
    )

    In this way, #drop will be displayed when the mouse enters #trigger. When the mouse moves from #trigger to #drop, no event will be triggered. In fact, the #trigger and #drop elements are treated as one element.

    jquery.mixhover.js program is as follows
    Copy code The code is as follows:

    /**
    * Author: http://rainman.cnblogs.com/
    * Date: 2014-06-06
    * Depend: jQuery
    */
    $.mixhover = function() {
    // Organize parameters $.mixhover($e1, $e2, handleIn, handleOut)
    var parms;
    var length = arguments.length;
    var handleIn = arguments[length - 2];
    var handleOut = arguments[length - 1];
    if ($.isFunction(handleIn) && $.isFunction(handleOut )) {
    parms = Array.prototype.slice.call(arguments, 0, length - 2);
    } else if ($.isFunction(handleOut)) {
    parms = Array.prototype.slice .call(arguments, 0, length - 1);
    handleIn = arguments[length - 1];
    handleOut = null;
    } else {
    parms = arguments;
    handleIn = null ;
    handleOut = null;
    }

    // Arrange parameters so that elements correspond in turn to
    var elems = [];
    for (var i = 0, len = parms.length ; i elems[i] = [];
    var p = parms[i];
    if (p.constructor === String) {
    p = $(p);
    }
    if (p.constructor === $ || p.constructor === Array) {
    for (var j = 0, size = p.length; j < ; size; j ) {
    elems[i].push(p[j]);
    }
    } else {
    elems[i].push(p);
    }
    }

    // Bind Hover event
    for (var i = 0, len = elems[0].length; i var arr = [] ;
    for (var j = 0, size = elems.length; j arr.push(elems[j][i]);
    }
    $. _mixhover(arr, handleIn, handleOut);
    }
    };
    $._mixhover = function(elems, handleIn, handleOut) {
    var isIn = false, timer;
    $(elems ).hover(function() {
    window.clearTimeout(timer);
    if (isIn === false) {
    handleIn && handleIn.apply(elems, elems);
    isIn = true ;
    }
    },
    function() {
    timer = window.setTimeout(function() {
    handleOut && handleOut.apply(elems, elems);
    isIn = false ;
    }, 10);
    });
    };
    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

    The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

    The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

    Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

    Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

    Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

    Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

    The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

    The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

    JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

    Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools