【问题标题】:.unbind() and .bind() function in hover function悬停函数中的 .unbind() 和 .bind() 函数
【发布时间】:2012-07-09 23:10:39
【问题描述】:

我正在尝试制作一个悬停功能,它在悬停时会取消绑定之前绑定的功能。

但我不认为我理解 jquery 网站试图解释的内容。

请在jsfiddle 中查看我的尝试。 http://jsfiddle.net/motocomdigital/S9uVh/

这是我的绑定函数,运行良好...

$("h1.trunc").bind().shorten({
    width: 300,
    tail: '...',
    tooltip: false 
});

但是当我的元素悬停时,我试图 .unbind() 它,但是在我的第二次悬停交替时重新绑定它......

$('#element').hover(
    function () {

        $(this).find("h1.trunc").unbind();

        $(this).animate({
            height : '100px'    
        }, 200 );       

    }, 
    function () {

        $(this).find("h1.trunc").bind().shorten({
            width: 300,
            tail: '...',
            tooltip: false
        });

        $(this).animate({
            height : '20px'    
        }, 200 );

    }
);​

请有人帮我解决这个问题。还有一种方法不必在我的悬停函数中重新编写整个“h1.trunc”函数。

请参阅工作jsfiddle here。提前致谢。

http://jsfiddle.net/motocomdigital/S9uVh/

【问题讨论】:

  • css overflow: visable;overflow: visible; 中的小错误

标签: jquery bind unbind


【解决方案1】:

如果您查看 shorten 实际在做什么,它正在删除文本,并且此方法没有反向操作,例如unshorten.

如果我理解正确,您希望在悬停时显示文本,然后在悬停时再次截断它。

我会摆脱shorten 插件,只使用css。看看这个小小提琴:http://jsfiddle.net/S9uVh/22/

基本上我只是删除一个类,然后再添加它。 <h1> 标签使用短接;

text-overflow: ellipsis;
overflow: hidden;    
white-space: nowrap;

【讨论】:

  • 出于某种原因,我认为 text-overflow css 仅限于浏览器支持???但是刚刚检查了一下,是的,它似乎适用于所有浏览器。谢谢!
  • 是的,这是您认为在 IE6/7 中无法使用但实际上可以使用的样式之一!
【解决方案2】:

嗯,你似乎误解了一些事情。首先,.bind() 单独放置(即没有参数)什么都不做。其次:这个.shorten 插件似乎改变了内部HTML,没有binding。而且它不允许返回到以前的状态。所以我建议你应该这样做:

HTML

<h1 class="trunc" data-text="This is a truncated title to untruncate when hovered using unbind tricks"></h1>

请注意,我将所有文本都放在了data-text 属性中。现在在你的处理程序中你这样做:

JavaScript

var text = $("h1.trunc").attr("data-text");

$('#element').hover(
    function () {

        $(this).find("h1.trunc").text(text);

        $(this).animate({
            height : '100px'    
        }, 200 );       

    }, 
    function () {

        $(this).find("h1.trunc").text(text).shorten({
            width: 300,
            tail: '...',
            tooltip: false
        });

        $(this).animate({
            height : '20px'    
        }, 200 );
    }
);​

结帐this jsFiddle。但是请注意,这个.shorten 插件似乎设置了nowrap css,这使它看起来很糟糕。您可以更改所有必要的样式,但编写自己的.shorten 函数可能更容易。 :]

【讨论】:

  • 这是一个非常聪明的主意。感谢您的时间和帮助。
【解决方案3】:

工作演示: http://jsfiddle.net/S9uVh/30/

我存储了每个标题的原始文本,还存储了每个标题的缩短文本。在#element 悬停时,最近的 h1 文本将替换为原始文本。将鼠标悬停在其上时,其文本将设置回缩短的版本。

【讨论】:

    【解决方案4】:

    你做错了什么。

    用法是

    .bind( eventType [, eventData], handler(eventObject) )
    

    .unbind( [eventType] [, handler(eventObject)] )
    

    另外 *bind () 已被弃用,您应该使用 on()off()

    【讨论】:

    • 感谢关于折旧的注意事项。我认为绑定是相当新的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2018-09-15
    相关资源
    最近更新 更多