javascript - 用 JS 面向对象编程改变 CSS

标签 javascript jquery html css oop

我想通过 OOP JS 更改 span 的 CSS 值。

鼠标悬停在照片上,文本的主体“发生变化”,即一个跨度消失,另一个跨度出现。

$(Document).ready(function(){
    $('#blackSquare').mouseenter(function(){
        $('#originalContent').css('display', 'none');
        $('#photo').css('display', 'table-cell');
    });
    $('#blackSquare').mouseleave(function(){
        $('#photo').css('display', 'none');
        $('#originalContent').css('display', 'table-cell');
    });
});

我需要为我想要影响 css 的每个对象执行上述代码。有没有一种简单的 OOP 方法可以做到这一点?

最佳答案

没有那么多OOP,但基本上您有两个选择:

  1. 如果鼠标与之交互的元素与您要显示/隐藏的元素之间存在任何类型的结构关系(父/子、同级、父级的同级被删除两次,等等),那么您可以从$(this)(鼠标与之交互的元素周围的 jQuery 包装器)并使用 various traversal methods找到您想要显示/隐藏的内容。

    例如,为了论证,我们假设 blackSquarephotooriginalContent 都在类 容器。我们还假设 photooriginalContentclasses 而不是 id。然后:

    $('#blackSquare').mouseenter(toggleContent.bind(undefined, true));
    $('#blackSquare').mouseleave(toggleContent.bind(undefined, false));
    function toggleContent(flag) {
        var container = $(this).closest('.container');
        container.find('.originalContent').css('display', flag ? 'none' : 'table-cell');
        container.find('.photo').css('display', flag ? 'table-cell' : 'none');
    }
    
  2. 如果没有结构关系,可以将要显示/隐藏的元素的id存储在元素的data-*属性中鼠标与之交互,然后通过 $(this).attr("data-foo") (例如)获取这些值,并在您的显示/隐藏选择器中使用它们。 (或者你可以使用 data,但如果你所做的只是读取 data-* 属性,那么 data 就太过分了。)所以在你的示例代码,例如,您会将 idphotooriginalContent 存储在 blackSquare 元素上。例如:

    $('#blackSquare').mouseenter(toggleContent.bind(undefined, true));
    $('#blackSquare').mouseleave(toggleContent.bind(undefined, false));
    function toggleContent(flag) {
        var $this = $(this),
            photoId = $this.attr("data-photo-id"),
            contentId = $this.attr("data-original-content-id");
        $('#' + photoId).css('display', flag ? 'none' : 'table-cell');
        $('#' + contentId).css('display', flag ? 'table-cell' : 'none');
    }
    

关于javascript - 用 JS 面向对象编程改变 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193396/

相关文章:

用于多个标签的 Python 正则表达式

html - 列表项文本在图标下不断换行

javascript - 如何提取Google结果页面中的搜索结果总量

javascript - 对象 foo 没有方法 'toLowercase'

javascript - HTML 下拉列表 - 整理?

javascript - 我不记得如何在 javascript 中使用/*

javascript - 动态改变特定div的颜色

php - 实时从mysql中获取数据

javascript - 标题中的多个按钮

javascript - 当从 javascript jQuery 单击按钮时,如何自动更改表单中的值?