我想通过 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,但基本上您有两个选择:
如果鼠标与之交互的元素与您要显示/隐藏的元素之间存在任何类型的结构关系(父/子、同级、父级的同级被删除两次,等等),那么您可以从
$(this)
(鼠标与之交互的元素周围的 jQuery 包装器)并使用 various traversal methods找到您想要显示/隐藏的内容。例如,为了论证,我们假设
blackSquare
、photo
和originalContent
都在类容器
。我们还假设photo
和originalContent
是 classes 而不是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'); }
如果没有结构关系,可以将要显示/隐藏的元素的
id
存储在元素的data-*
属性中鼠标与之交互,然后通过$(this).attr("data-foo")
(例如)获取这些值,并在您的显示/隐藏选择器中使用它们。 (或者你可以使用data
,但如果你所做的只是读取data-*
属性,那么data
就太过分了。)所以在你的示例代码,例如,您会将id
的photo
和originalContent
存储在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/