开发者

Dynamically change an element's top position based on height

I have three divs that are set to popup on li:hover using CSS. I want these divs to hover at the same level above their parent li regardless of the height of their content. In order to do so, I'm trying to use jquery to calculate the div's height, then set a negative to开发者_如何学Cp value equal to the height of the div. Here's what I have so far:

<script type="text/javascript">
$(document).ready(function() {
var pHeight = $('footer ul ul').height(); //Get height of footer popup
var nHeight = pHeight + "px"; //Calculate new top position based on footer popup height

        $('footer ul ul').css({ //Change top position to equal height of footer popup
            'top' : "-nHeight",
    });
});
</script>

Firebug keeps telling me that there was an error parsing the value for top and the declaration was dropped. Any thoughts?


Change

'top' : "-nHeight",

to

'top' : "-" + nHeight

JavaScript does not parse variables inside of strings. I've also removed the , since it's redundant and it will produce an error in IE.


You need to remove the quotes to use the variable, otherwise it's trying to parse the literal string "-nHeight" as a number:

<script type="text/javascript">
$(document).ready(function() {
  var pHeight = $('footer ul ul').height();
  var nHeight = pHeight;    
  $('footer ul ul').css({
     'top' : -nHeight
  });
});
</script>

Or, the more compact version:

<script type="text/javascript">
$(function() {   
  $('footer ul ul').css({ top: -$('footer ul ul').height() });
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜