javascript - 我怎样才能在js中制作更小的js代码?

标签 javascript jquery css

我在悬停功能的按钮中有 5 个具有不同类型颜色的 css 类,在我的页面中可能有 5 个具有不同类的按钮。当我将鼠标悬停在每个按钮上时,颜色应该根据各自的类名设置,到目前为止它对我来说工作正常。但现在我可以看到巨大的代码,我想把它变小。请推荐任何人。

$('[class^="button"]').parent().each(function(){
    var parentElement = $(this);
    var buttonfullwidth = $(parentElement).hasClass('buttonfullwidth');
    var buttonfullwidth_1 = $(parentElement).hasClass('buttonfullwidth_1');
    var buttonfullwidth_2 = $(parentElement).hasClass('buttonfullwidth_2');
    var buttonfullwidth_3 = $(parentElement).hasClass('buttonfullwidth_3');
    var buttonfullwidth_4 = $(parentElement).hasClass('buttonfullwidth_4');

    if(buttonfullwidth_1 !== false) {
        $(parentElement).hover(function(){
            $(this).addClass('buttonfullwidth_1');

        }, function(){
            $(this).removeClass('buttonfullwidth_1');

        });
    }
    if(buttonfullwidth_2 !== false) {
        $(parentElement).hover(function(){
            $(this).addClass('buttonfullwidth_2');

        }, function(){
            $(this).removeClass('buttonfullwidth_2');

        });
    }
    if(buttonfullwidth_3 !== false) {
        $(parentElement).hover(function(){
            $(this).addClass('buttonfullwidth_3');

        }, function(){
            $(this).removeClass('buttonfullwidth_3');

        });
    }
    if(buttonfullwidth_4 !== false) {
        $(parentElement).hover(function(){
            $(this).addClass('buttonfullwidth_4');

        }, function(){
            $(this).removeClass('buttonfullwidth_4');

        });
    }
    if(buttonfullwidth !== false) {
        $(parentElement).hover(function(){
            $(this).addClass('buttonfullwidth');

        }, function(){
            $(this).removeClass('buttonfullwidth');

        });
    }
});

最佳答案

您需要使用 :hover 来完成这项工作的 CSS伪选择器

The :hover CSS pseudo-class matches when the user interacts with an element with a pointing device, it is generally triggered when the user hovers over an element with the mouse pointer.

例如,如果您希望此按钮在悬停时变为蓝色:

.myButton {
  background-color: lightgreen;
}

.myButton:hover {
  background-color: lightblue;
}
<button class="myButton">Hover this button</button>

请注意当元素处于悬停状态时我如何为该元素设置属性。

因此对于您的代码,您只需使用以下选择器:

buttonfullwidth
buttonfullwidth:hover

buttonfullwidth_1
buttonfullwidth_1:hover

buttonfullwidth_2
buttonfullwidth_2:hover

buttonfullwidth_3
buttonfullwidth_3:hover

buttonfullwidth_4
buttonfullwidth_4:hover

与我在示例中所做的方式相同。

关于javascript - 我怎样才能在js中制作更小的js代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172246/

相关文章:

html - 修复简单容器中 div 的重叠问题

javascript - 圆形对象内的图像导致像素化 d3 js

javascript - 猫头鹰轮播2导航

css - 我可以使用 Homestead sitebuilder 为我的网站编写绝对定位元素吗?

jquery - 为什么 $ (":select").focus 不起作用,而 $ (":input").focus 起作用?

java - 如何获取有关更新数据库的推送通知

javascript - 动态生成菜单的动画无法正常工作

javascript - 表 td 上的 JQuery 鼠标悬停文本?

javascript - 如何在 plotly js 中创建水平阈值线?

javascript - while 循环中的链接 promise 未正确返回值