使用HTML扩展图像&Jquery

Image expansion with HTML & Jquery

本文关键字:Jquery 图像 扩展 HTML 使用      更新时间:2023-09-26

我看到了这段代码,并试图模仿它,但它在我的电脑或浏览器上不起作用

<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script>
var current_h = null;
var current_w = null;
$('.resize').hover(
    function(){
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).stop(true, false).animate({width: (current_w * 1.3), height: (current_h * 1.3)}, 300);
    },
    function(){
        $(this).stop(true, false).animate({width: current_w + 'px', height: current_h + 'px'}, 300);
    }
);
</script>
<div class="box">
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250"/>
</div>
</body>
</html>

谁能告诉我我哪里做错了?

把它放在你的CSS链接下面,在你的<head>标签里面。

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

你想让它在什么浏览器中工作?

更新:

用:

$(document).ready(function() {
    // Code here...
});

如果你看一下fiddle的代码,整个函数都在"load"事件中。试试那个或ready函数

$(window).load(function(){
    var current_h = null;
    var current_w = null;
    $('.resize').hover(
        function(){
            current_h = $(this, 'img')[0].height;
            current_w = $(this, 'img')[0].width;
            $(this).stop(true, false).animate({width: (current_w * 1.3), height: (current_h * 1.3)}, 300);
        },
        function(){
            $(this).stop(true, false).animate({width: current_w + 'px', height: current_h + 'px'}, 300);
        }
    );
});

将这段代码包装在document.ready中并不是一个坏主意:

$(document).ready(function() {
    $('.resize').hover(
        function() {
            current_h = $(this, 'img')[0].height;
            current_w = $(this, 'img')[0].width;
            $(this).stop(true, false).animate({width: (current_w * 1.3), height: (current_h * 1.3)}, 300);
        },
        function() {
            $(this).stop(true, false).animate({width: current_w + 'px', height: current_h + 'px'}, 300);
        }
    );
});

$(document).ready添加到javascript代码中并更新您的代码。这是新的

<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script>
var current_h = null;
var current_w = null;
$(document).ready(function () {
  $('.resize').hover(
    function () {
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).stop(true, false).animate({
            width: (current_w * 1.3),
            height: (current_h * 1.3)
        }, 300);
    },
    function () {
        $(this).stop(true, false).animate({
            width: current_w + 'px',
            height: current_h + 'px'
        }, 300);
  });
});
</script>
<div class="box">
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250"/>
</div>
</body>
</html>