【问题标题】:Partially showing/hiding an element with jQuery使用 jQuery 部分显示/隐藏元素
【发布时间】:2012-03-06 20:09:14
【问题描述】:

我有这个基本脚本,它使元素显示 onmouseenter,并隐藏 onmouseleave。 在 HTML 版本中工作正常,但我需要在 wordpress 中显示它;但在 WP 中不起作用。

Firebug 显示以下错误:

sidebar_animate 未定义

我该如何解决这个问题?

脚本

<script language="javascript">

    function sidebar_animate(px) {
       $('#sidebar').animate({
       'marginLeft' : px
     });
}
</script>

身体

<div id="sidebar" onmouseenter="sidebar_animate('+180px');" 
  onmouseleave="sidebar_animate('-20px');"
  style="background-color: red; width: 240px; height: 100px; position: absolute; left: -180px;" >
  This is going to move
</div>

【问题讨论】:

  • 当您签入 firebug 时,您是否看到页面中的脚本?

标签: javascript jquery wordpress show-hide


【解决方案1】:

如何使用 jQuery 绑定事件处理程序,以便您的代码集中在一处:

<script language="javascript">

//wait for document.ready to fire so elements are available to manipulate
$(function () {

    //setup object to convert the type of event fired to the pixel offset to apply for the event
    var eventToPx = {
        mouseenter : 180,
        mouseleave : -20
    };


    //bind an event handler to the `#sidebar` element for `mouseleave` and `mouseenter`
    $('#sidebar').on('mouseenter mouseleave', function (event) {

        //animate this element's `margin-left` property to the specified number of pixels
        //note that jQuery assumes pixels if you omit units
        $(this).stop().animate({
            marginLeft : eventToPx[event.type]
        }, 500);
    });
});
</script>

这是一个演示:http://jsfiddle.net/jasper/mYwqE/

请注意,我在.animate() 调用之前将.stop() 添加到您的代码中。如果有新动画排队,它将停止当前动画,因此如果用户快速多次鼠标悬停和鼠标移出元素,动画将不会排队。

请注意,.on() 是 jQuery 1.7 的新内容,在这种情况下与使用 .bind() 相同:http://api.jquery.com/on

【讨论】:

  • 谢谢 Jasper,非常感谢您抽出时间为我开发和解释这段代码。你救了我的命!!
  • 注意:要在 Wordpress 中使用此代码,请将所有“$”符号更改为 jQuery:$(function () { 到 jQuery(function () {
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多