【问题标题】:Why won't the margin-top property update using jQuery.animate?为什么不使用 jQuery.animate 更新 margin-top 属性?
【发布时间】:2009-10-07 09:54:45
【问题描述】:

我第一次玩 jQuery,制作了一个小照片滑块插件来让我的脚湿透。我似乎无法在我的标签上更新 margin-top 属性。我以为边距正在崩溃,但现在我不太确定。请给我亮光!

我认为问题在于 .slider-frame 上的 10px 边距和 .photo-slider 上的 -58px 边距,但如果它们折叠起来,它们之间的边距应该是 -48px,对吧?使用萤火虫,当我将鼠标悬停在图像上时,margin-top 属性永远不会从 10px 改变。

这是我正在生成的 HTML:

<div id="photos" class="photo-slider-container">
  <div class="photo-slider">
    <img class="slider-frame" src="images/test-image.jpg"/>
    <img class="slider-frame" src="images/test-image-2.jpg"/>
    <img class="slider-frame" src="images/test-image-3.jpg"/>
    <img class="slider-frame" src="images/test-image-4.jpg"/>
    <img class="slider-frame" src="images/test-image-5.jpg"/>
  </div>
</div>

这是提取的 CSS,用 jQuery 生成,以便您阅读:

.photo-slider-container{
    overflow: hidden; 
    visibility: visible; 
    position: relative; 
    background-color: rgb(0, 0, 0); 
    height: 216px; 
    width: 800px; 
    margin-left: auto; 
    margin-right: auto;
}

.photo-slider {
    margin: -58px 0px 0px -580px;
    position: absolute;
    padding-top: 1px;
    left: 50%;
    top: 50%;
    width: 1160px;
}

.slider-frame {
 margin: 10px 5px; 
 float: left; 
 width: 96px; 
 height: 96px;
}

这是悬停代码:

$(this).hover(
  function(){
   $(this).stop().animate({
      "height" : opts.large_image_height,
      "width" : opts.large_image_width,
      "margin-top" : opts.large_image_height / -2 + "px"
    }, { duration : 250 })
  },
  function() {
    $(this).stop().animate({
      "height" : opts.small_image_height,
      "width" : opts.small_image_width,
      "margin-top" : "10px"
    }, { duration : 250 })
  }
);

编辑 顶一下jsbin

【问题讨论】:

  • 你能在jsbin.com上发布一个演示吗?
  • opts.large_image_height 等是如何计算的?我们可以看看计算这些的脚本吗?
  • jsbin.com 非常简洁!谢谢拉斯。
  • 你用的是最新的jQuery吗?
  • @Matt - 没有问题,jsbin 非常适合快速尝试想法和协作代码:)

标签: jquery css


【解决方案1】:

啊 - 它是 ma​​rginTop。 - 我猜内部动画解析器不会将 'margin-top' 转换为 real marginTop。

示例:http://jsbin.com/uxazo

注意:您的脚本将在 IE 中失败,因为您的对象中有尾随逗号:

{
one:1,
two:2, <---- get rid of this.
}

【讨论】:

  • .. 高度评估为多少。你可以通过简化这个来轻松解决这个问题......
  • 是的,我知道尾随逗号。谢谢。现在我只需要正确计算即可。
【解决方案2】:

看来我来不及了 - 它是 marginTop 而不是 margin-topanimate() 内。您正在寻找的是 something like this 吗?

无论如何我都会回答你可能会考虑的另一项改进是将$(this) 缓存在each() 命令中的局部变量中,即

    return this.each(function() { 

  Cache this ->  $(this).wrap("<div></div>"); 
                 slider_container = $(this).parent(); 

现在变成了

    return this.each(function() { 
        var $this = $(this);
        $this.wrap("<div></div>"); 
        slider_container = $this.parent(); 

这意味着每次调用 $() 传入 this 时都不会构造一个新的 jQuery 对象

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
相关资源
最近更新 更多