简体   繁体   中英

Make JS menu show on hover rather than on click

I've got Dropdown Menu 3 from here: http://tympanus.net/codrops/2012/10/04/custom-drop-down-list-styling/

Working well onclick, but I don't know how to make it work on hover.

My attempt at the JS:

<script type="text/javascript">

        function DropDown(el) {
            this.dd = el;
            this.placeholder = this.dd.children('span');
            this.opts = this.dd.find('ul.dropdown > a');
            this.val = '';
            this.index = -1;
            this.initEvents();
        }
        DropDown.prototype = {
            initEvents : function() {
                var obj = this;

                obj.dd.on('hover', function(event){
                    $(this).toggleClass('active');
                    return false;
                });

                obj.opts.on('hover',function(){
                    var opt = $(this);
                    obj.val = opt.text();
                    obj.index = opt.index();
                    obj.placeholder.text(obj.val);
                });
            },
            getValue : function() {
                return this.val;
            },
            getIndex : function() {
                return this.index;
            }
        }

        $(function() {

            var dd = new DropDown( $('#dd') );

            $(document).hover(function() {
                // all dropdowns
                $('.wrapper-dropdown-3').removeClass('active');
            });

        });

    </script>

I think this should work:

 $(function() {

        var dd = new DropDown( $('#dd') );

        $('.wrapper-dropdown-3').hover(function() {
            $(this).toggleClass('active');
        });

    });

If got any issues, say so.

Try:

            obj.dd.on('mouseenter', function(event){
                $(this).toggleClass('active');
                return false;
            });

            obj.opts.on('mouseleave',function(){
                var opt = $(this);
                obj.val = opt.text();
                obj.index = opt.index();
                obj.placeholder.text(obj.val);
            });

If I am not mistaken, the hover() function looks for mouseover and mouseoff events. Why would you want the menu to only change when your mouse is over an item at the top? Once you mouseoff it will change. I recommend using just mouseover, and then a mouseleave instead of hover.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM