首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jQuery部分显示/隐藏元素

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

Stack Overflow用户
提问于 2012-03-06 20:09:14
回答 1查看 293关注 0票数 1

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

Firebug显示以下错误:

未定义

sidebar_animate

我怎么才能解决这个问题?

脚本

代码语言:javascript
复制
<script language="javascript">

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

正文

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-06 20:13:15

如何将事件处理程序绑定到jQuery,以便您的代码都在一个位置上:

代码语言:javascript
复制
<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/

注意,我在.stop()调用之前将.animate()添加到您的代码中。如果一个新的动画被排队,它将停止当前的动画,所以如果用户鼠标越出和鼠标退出的元素多次快速排队,动画就不会排队。

请注意,.on()在jQuery 1.7中是新的,在本例中与使用.bind():http://api.jquery.com/on相同

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9591061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档