我正在寻找一种更优雅的方式来使用内联 Javascript 隐藏/显示 div。
如果您将鼠标悬停在汽车上方的橙色/黄色圆圈 Logo 上,则应该会出现标签。当鼠标移出时,它们应该消失。
网址:
http://174.120.239.48/~peakperf/
<div class="second">
<div id="speech2" style="display: none">
<img src="<?php bloginfo('template_url'); ?>/images/speech2.png" width="334" height="50">
</div>
<a id="various2" href="#inline2,javascript:HideContent('speech1')" title="" onmouseover="HideContent('speech1'); return true;">
<img src="<?php bloginfo('template_url'); ?>/images/clicker.png" width="62" height="50" onmouseover="document.getElementById('speech2').style.display = 'block'" onmouseout="document.getElementById('speech2').style.display = 'none'">
</a>
</div>
这是所使用代码的pastebin:
最佳答案
更优雅的解决方案是利用 JQuery。 将库包含到文件中后,将使用以下选择器完成 div 显示
$('#idOfDiv').show();
或者如果没有 id,而是类
$('.ClassName').show();
现在,您不必像现在那样在 html 中添加 onclick 事件,只需将它们绑定(bind)在 jquery 的 read() 方法中,如下所示:
$(document).ready(function()
{
$('#idOfDiv').bind('click', function()
{
//do work here in this anonymous callback function
});
});
所有这些都可以在外部 js 文件中完成,这样可以显着清理您的 html 代码 并将所有 JavaScript 逻辑放入一个位置。
编辑: 适用于您的情况的示例
$(document).ready(function()
{
$('#various1').mouseover(function()
{
$('#speech1').show();
});
$('#various1').mouseout(function()
{
$('#speech1').hide();
});
});
如果你很狡猾并利用 for 循环,那么你可以将数字附加到代表选择器的字符串末尾,如下所示
$(document).ready(function()
{
for(var i = 1; i < 7; i++)
{
$('#various' + i).mouseover(function()
{
$('#speech' + i).show();
});
$('#various' + i).mouseout(function()
{
$('#speech' + i).hide();
});
}
});
mouseout 和 mouseover 函数只是像这样使用的显式版本
$('selector').bind('mouseover', function()
{
});
$('selector').bind('mouseout', function()
{
});
关于Javascript 隐藏/显示 - 更优雅的方式来做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226294/