Javascript 使用jQuery部分显示/隐藏元素

Javascript 使用jQuery部分显示/隐藏元素,javascript,jquery,wordpress,show-hide,Javascript,Jquery,Wordpress,Show Hide,我有一个基本的脚本,它使一个元素在mouseenter上显示,在mouseeve上隐藏。 在HTML版本的工作很好,但我需要在wordpress中显示它;但是,在WP中,它不起作用 Firebug显示以下错误: 未定义侧边栏_动画 我怎样才能解决这个问题 剧本 函数侧栏_动画(px){ $(“#侧边栏”)。设置动画({ “marginLeft”:px }); } 身体 这就要动了 如何将事件处理程序与jQuery绑定,使您的代码集中在一个位置: <script language="j

我有一个基本的脚本,它使一个元素在mouseenter上显示,在mouseeve上隐藏。 在HTML版本的工作很好,但我需要在wordpress中显示它;但是,在WP中,它不起作用

Firebug显示以下错误:

未定义侧边栏_动画

我怎样才能解决这个问题

剧本

函数侧栏_动画(px){
$(“#侧边栏”)。设置动画({
“marginLeft”:px
});
}
身体

这就要动了

如何将事件处理程序与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>

//等待document.ready启动,以便可以操纵元素
$(函数(){
//setup对象将激发的事件类型转换为像素偏移以应用于事件
var eventToPx={
鼠标指针:180,
穆斯勒夫:-20
};
//将事件处理程序绑定到`mouseleave`和`mouseenter`的`sidebar`元素`
$(“#侧边栏”).on('mouseenter mouseleave',函数(事件){
//将此元素的“margin left”属性设置为指定的像素数
//请注意,如果省略单位,jQuery将采用像素
$(this).stop().animate({
marginLeft:eventToPx[event.type]
}, 500);
});
});
下面是一个演示:

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


请注意,
.on()
从jQuery 1.7开始是新的,在这种情况下与使用
.bind()
相同:

当您签入firebug时,您看到页面中的脚本了吗?谢谢Jasper,我非常感谢您抽出时间为我开发和解释此代码。你救了我的命!!注意:要在Wordpress中使用此代码,请将所有“$”符号更改为jQuery:$(函数(){更改为jQuery(函数(){
<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>
<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>