在hover时更改文本,然后返回上一个文本
我有一个评论系统,每个评论都有一个按钮,通常显示回复的数量。 我希望当用户将鼠标hover在按钮上时,文本会从“3回复”变为“回复!”,然后,当鼠标离开按钮时,文本将返回“3回复”。
因为每个评论的回复数量各不相同,所以我不能做一个简单的mouseover / mouseout脚本。 绕过它的一种方法是将回复的数量作为变量传递,并使用一个小函数来处理它。 但必须有一个更简单的方法。 我尝试在css中使用:hover事物来更改标记的内容(使用css属性内容),但还没有运气。
任何帮助表示感谢,谢谢!
是的,您可以使用CSS content
。 要在普通文本和“回复!”之间切换,请将正常文本放在span
并在hover时隐藏它。
HTML:
CSS:
button {width:6em} button:hover span {display:none} button:hover:before {content:"Reply!"}
的jsfiddle:
编辑:这适用于IE8,但不适用于兼容模式,所以我假设IE7已经出局。 那会有问题吗?
我认为这将是一种直截了当的方式。 在按钮内使用两个跨度,一个内容为“x回复”,另一个内容为“回复!”。 使用CSS和:hover,您只需切换hover时显示的跨度。
HTML:
CSS:
button .comment { display: none; } button:hover .replies { display: none; } button:hover .comment { display: inline; }
检查JsFiddle示例。 这对于所有事情都很好,因为它使用非常基本的东西来实现同样的基本目标。
我会使用jQuery .hover()和jQuery .data()的组合:
HTML:
default text
JavaScript的:
$('#myDiv') .data('textToggle', 5) .hover(function (e) { var that = $(this); // get the text from data attribute var textToSet = that.data('textToggle'); // save the current text so it can be reverted that.data('textToggle', that.text()); // set the new text that.text(textToSet); }, function (e) { var that = $(this); // get the text from data attribute var textToSet = that.data('textToggle'); // save the current text so it can be reverted that.data('textToggle', that.text()); // set the new text that.text(textToSet); });
编辑:随意重构用作hover的两个回调的匿名函数,因为它们完全相同:)
$('#button_id').hover( function(){ $(this).text('Reply!'); }, function(){ $.ajax({ url: 'script.php', type: 'post', data: comment_id, success: function(num_replies){ $('#button_id').text(num_replies + ' replies'); } }); } );
我认为您可以使用这种function,当您停止hover时,您将ajax调用您的注释ID,并返回该注释的回复数。 您可以决定如何存储/检索评论ID。
如果有人想在菜单链接上尝试相同的,(hover时的不同语言文本)这里是jsfiddle示例
HTML:
kannada
CSS:
span { font-size:12px; } a { color:green; } a:hover span { display:none; } a:hover:before { color:red; font-size:24px; content:"ಕನ್ನಡ"; }
另一种方法是使用按钮创建两个跨度,并为每个跨度创建类。
将第二个留空,并在css中写:
button{ //your decorative code here } button:hover .replies{ display: none; } button:hover .comments:before{ content:"Reply!"; }
这与第一个答案类似,但该答案并不总是适用于像SASS或LESS这样的预处理器。
尽可能简单:
$('.controls button.filter').hover(function(){ var original = $('#current_filter').text(); var descr = $(this).attr("title"); $('#current_filter').html( descr ); }, function() { $('#current_filter').text(original); });