admin管理员组

文章数量:1325236

I'm trying to follow this SO answer on how to tint an image, but when i do it, $("#myselector").height(); keeps been returned as 0. What am I doing wrong? Heres my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Test</title>
    <link rel="stylesheet" href="style.css">
    <!--[if IE]>
        <script src=".js"></script>
    <![endif]-->
</head>
<script src=".10.2.min.js"></script>

<script>
$(document).ready(function() {
  overlay = $("#overlay");
img = $("#myimg");
overlay.width($("#myimg").width());
alert($("#myimg").height());
overlay.height("100");
overlay.css("top", img.offset().top + "px");
overlay.css("left", img.offset().left + "px");

});


</script>

<body id="home">

<div id="overlay" class="overlay"></div>
<img id="myimg" src="building.png" />

</body>
</html>

I'm trying to follow this SO answer on how to tint an image, but when i do it, $("#myselector").height(); keeps been returned as 0. What am I doing wrong? Heres my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Test</title>
    <link rel="stylesheet" href="style.css">
    <!--[if IE]>
        <script src="http://html5shiv.googlecode./svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<script src="http://codeorigin.jquery./jquery-1.10.2.min.js"></script>

<script>
$(document).ready(function() {
  overlay = $("#overlay");
img = $("#myimg");
overlay.width($("#myimg").width());
alert($("#myimg").height());
overlay.height("100");
overlay.css("top", img.offset().top + "px");
overlay.css("left", img.offset().left + "px");

});


</script>

<body id="home">

<div id="overlay" class="overlay"></div>
<img id="myimg" src="building.png" />

</body>
</html>
Share Improve this question edited May 23, 2017 at 12:14 CommunityBot 11 silver badge asked Aug 12, 2013 at 12:14 MissCoder87MissCoder87 2,66910 gold badges49 silver badges82 bronze badges 1
  • on your source , he use overlay.height(img.css("height")); – Janith Chinthana Commented Aug 12, 2013 at 12:19
Add a ment  | 

3 Answers 3

Reset to default 5

My best guess is that the image isn't loaded yet.

Your script runs onready. If you change it to onload you'll probably get a better result.

Change

$(document).ready(function() {

to

$(window).load(function() {

More: window.onload vs $(document).ready()

Use image' load event:

$(document).ready(function() {
  overlay = $("#overlay");
  img = $("#myimg");
  img.load( function(){
    overlay.width($("#myimg").width());
    alert($("#myimg").height());
    overlay.height("100");
    overlay.css("top", img.offset().top + "px");
    overlay.css("left", img.offset().left + "px");
  });
});

Replace:

$(document).ready(function() {

on:

$(window).load(function() {

本文标签: javascriptImage height always returned as 0Stack Overflow