【发布时间】:2012-02-29 15:23:56
【问题描述】:
jQuery noob 在这里(大多数帖子不是这样开头的吗?)
我知道我可以单独使用 CSS 来做到这一点,但为了让体验更具触觉,我正在尝试编写一个 jQuery“剧透”函数,如果页面上的一些文本标记得当,它会混淆它并在鼠标悬停时显示。
总的来说,这很好用 - 它用您选择的一些文本替换文本,甚至匹配被替换文本的宽度以阻止文本重排。当我在页面上添加多个扰流器类时,问题就出现了——在这种情况下,它连接了每个扰流器中的文本,并且似乎与元素第一个匹配元素的宽度相匹配。这基本上就像函数无法区分每个扰流板之间的区别,所以它将它们放在一起。
我一定是在相当基本的层面上做错了什么。有人可以指出我的错误吗?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spoiler test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
jQuery.fn.spoiler = function(spoilerReplaceText) {
$(this).addClass('spoilerCensored');
var spoilerText = $(this).text();
var spoilerWidth = $(this).width();
$(this).attr('spoilertext',spoilerText).text(spoilerReplaceText).width(spoilerWidth);
$(this).stop().hover(
function(){
var spoilerText = $(this).attr('spoilertext');
$(this).fadeOut(250,function(){
$(this).text(spoilerText).addClass('spoilerRevealed').removeClass('spoilerCensored').fadeIn(250);
});
},
function(){
$(this).fadeOut(250,function(){
$(this).text(spoilerReplaceText).removeClass('spoilerRevealed').addClass('spoilerCensored').fadeIn(250);
});
}
);
};
$('.spoiler').spoiler("don't touch this");
});
</script>
<style type="text/css">
.spoiler {display: inline-block;background-color: #000000;color: #000000;text-align: center;}
.spoilerCensored {color: #ffffff;}
.spoilerRevealed {background-color: #ffffff;color: #000000;}
</style>
</head>
<body>
<p>You can add a <span class="spoiler">spoiler to your content</span> very easily. All you need to do is <span class="spoiler">add a class called spoiler to each bit of text</span> you'd like to hide. There is a problem with <span class="spoiler">adding</span> more than one spoiler to a page though.</p>
</body>
</html>
【问题讨论】:
-
混淆“剧透文本”的最简单方法就是使其与背景颜色相同,并在翻转时切换。打乱文本本身似乎有点过头了。
-
我同意,但是这个练习对我来说更像是一个挑战,而不是一个合适的商业项目。我想要实现的不是简单地清除混淆的文本,而是让用户能够定义显示的文本——因此效果很好。不过我不知道这是否是最好的方法 :) 我确信 XHTML 验证器会因为我使用的一些技术而对我大喊大叫!
标签: jquery class selector concatenation