”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用 JavaScript 创建可悬停的选择框选项?

如何使用 JavaScript 创建可悬停的选择框选项?

发布于2024-12-21
浏览:966

How to Create Hoverable Select Box Options with JavaScript?

可悬停选择框选项

当前的问题涉及创建一个选择框,当将字段悬停在该选择框上时,选项说明可见,而不是单击打开options.

实现

为了实现此功能,我们利用了 JavaScript 方法:如下:

$('#selectUl li:not(":first")').addClass('unselected');
// Hide the 'unselected' elements in the ul.

$('#selectUl').hover(
    function(){
    // mouse-over
        $(this).find('li').click(
            function(){
                $('.unselected').removeClass('unselected');
                // removes the 'unselected' style

                $(this).siblings('li').addClass('unselected');
                // adds 'unselected' style to all other li elements

                var index = $(this).index();
                $('select option:selected').removeAttr('selected');
                // deselects the previously-chosen option in the select

                $('select[name=size]')
                    .find('option:eq('   index   ')')
                    .attr('selected',true);
                // assumes a 1:1 relationship between the li and option elements
            });
    },
    function(){
    // mouseout (or mouseleave, if they're different, I can't remember).
    });

在此方法中,未选择的类用于最初隐藏除第一个选项之外的所有选项。当 ul 悬停在上方时,未单击的元素将被赋予未选择的类,从而有效地消失。所选元素保持可见,其相应值反映在底层选择字段中。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3