【问题标题】:Set width of one div based on another根据另一个设置一个div的宽度
【发布时间】:2014-12-23 14:02:17
【问题描述】:

我遇到了以下问题。每次用户单击锚点时,我都需要设置一个 div 的宽度。此 div 的宽度应取自另一个 div。如何做到这一点?

以下代码不起作用(请记住,该脚本包含在 PHP echo 中):

jQuery(".geother").click(function(){
var pos=$("p.second").width() + "px";
jQuery("#headerRightContactPhone span").css(\'width\', pos);
}

编辑(我还需要另外的东西,我想应用到“geother” div CSS left,这将是 pos width+230px 的负值):

jQuery(".geother").click(function(){
   var pos = $("p.second").width(); // don't need to use 'px'
   jQuery("#headerRightContactPhone span").css('width', pos); // don't need escaping
   $(this).css('left', ((230+pos)*-1) );
});

【问题讨论】:

  • 我从来没有使用过 span;应该在几年内被弃用,我希望......

标签: jquery css width


【解决方案1】:
jQuery(".geother").click(function(){
   var pos = $("p.second").width(); // don't need to use 'px'
   jQuery("#headerRightContactPhone span").css('width', pos); // don't need escaping
}); //  you missed ');' here

注意

您应该需要将display: block 提供给您的span 或使用任何块元素,例如div、p 等。

jQuery(".geother").click(function(){
       var pos = $("p.second").width(); // don't need to use 'px'
       jQuery("#headerRightContactPhone span").css({
                     width: pos, 
                     display: 'block',
                     left: '-' + (230+pos)
               }); // don't need escaping
    }); 

【讨论】:

  • 谢谢,您的回答非常好。我还编辑了第一篇文章,因为我需要另一个小的修改。你能看一下吗?
【解决方案2】:

您是否对 span 元素应用宽度?这就是问题所在。将 span 设为块或使用 div。

【讨论】:

  • A 是一个内联元素,没有隐含的“width”属性。
  • 添加关于“为什么”您不能向跨度添加宽度的说明。
猜你喜欢
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 2016-11-04
  • 2011-03-17
  • 2017-02-07
相关资源
最近更新 更多