【问题标题】:Weird height doubling bug on mouseover with jQueryjQuery 鼠标悬停时奇怪的高度加倍错误
【发布时间】:2011-05-26 11:02:51
【问题描述】:

我使用 jquery 和 javascript 创建了一些自定义翻转按钮功能,但我遇到了一个变量没有被覆盖而是添加到的问题。我的代码的基本功能是鼠标悬停在链接上,我只是希望链接向上滑动并加倍高度,以便显示图形的底部“打开”部分(就像 css 滑动门翻转一样)。

但是我遇到的问题是 doubleHeight 变量是累积的,因此每次翻转链接时,链接的双倍高度都不会每次都重置,它只是将其添加到最后一个值。奇怪的是,这仅在页面上触发灯箱后才会发生,在此之前功能正常工作。这是我的javascript:

var heightVal, doubleHeight;

$('div.flex_rollover_btn p a').bind('mouseover', function() {
    heightVal = $(this).css('height');
    doubleHeight = heightVal.replace("px", "");
    doubleHeight = doubleHeight * 2 + "px";
    $(this).css({height: doubleHeight, top: '-' + heightVal});
});

$('div.flex_rollover_btn p a').bind('mouseout', function() {
    heightVal = $(this).parent().css('height');
    $(this).css({height: heightVal, top: '0'});
});

这是它所作用的 HTML 代码:

<div style="position: absolute; top: 322px; left: 13px; width: 139px; height: 79px; z-index: 3;" class="block item_3 flex_rollover_btn">
    <p style="width: 75px; height: 53px;"><a style="width: 75px; height: 53px;" class="new_window" title="Flexible Size Rollover Test 2" href="http://doctype.tv"><img height="106" width="75" alt="Flexible Size Rollover Test 2" src="/cms/arcadiacorp_uk/repository/pages/static/static-0000006614/images/flex_rollover_2.gif"></a></p>
</div>

要查看它的运行情况go here 向右滚动并将鼠标悬停在红色星形物体上,然后打开一个灯箱(任何旁边带有 + 符号的链接)将其关闭并再次将鼠标悬停在红色星形物体上,然后你会明白我的意思。

【问题讨论】:

  • 如果将 div.flex_rollover_btn 高度加倍,那么父级高度也会增加(如果不够高)。因此,当您在 mouseout 事件中获取父级高度时,高度将与双倍高度相同。您需要存储之前的高度。
  • 嗨 Sani,这是我试过的: $('div.flex_rollover_btn p a').mouseover(function() { heightVal = $(this).css('height'); constantHeight = heightVal; doubleHeight = heightVal.replace("px", ""); doubleHeight = doubleHeight * 2 + "px"; $(this).css({height: doubleHeight, top: '-' + heightVal}); }) ; $('div.flex_rollover_btn p a').mouseout(function() { $(this).css({height: constantHeight, top: '0'}); });这就是你的意思吗,它没有工作。

标签: javascript jquery mouseover


【解决方案1】:

在你的 mouseout 处理函数中,你实际上并没有做任何事情。你得到 heightVal(之前加倍)并将其分配回去。简单的解决方案是在分配之前将值除以 2,就像在鼠标悬停函数中将其加倍一样。

最好的方法是使用 CSS 类来完成这一切。在 CSS 中,您可以指定所有尺寸,例如高度,然后在 JavaScript 中,您可以通过添加或删除类来简单地更改高度。

编辑:我在 mouseout 处理程序函数中看到您查看父级。您确定父元素没有使用子元素调整大小吗?

【讨论】:

  • (S)他实际上得到了父母的身高,但也翻了一番。
  • 大家好,我得到父身高的原因是因为这个 p 应该始终保持一个恒定的高度。我不确定你为什么认为它的高度增加了一倍,我使用 console.log 检查了鼠标悬停和鼠标悬停时 p 的高度,并且两者都记录了相同的未更改的值。注:我注意到 mouseover 触发了多次,所以我改用 mouseenter 和 mouseleave。
【解决方案2】:

我知道这不是直接解决您的问题,但不要这样做:

doubleHeight = heightVal.replace("px", "");
doubleHeight = doubleHeight * 2 + "px";

相反,这样做:

doubleHeight = (2 * parseInt(heightVal, 10)) + px;

【讨论】:

    猜你喜欢
    • 2013-04-02
    • 2011-08-04
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多