2016-07-04 3 views
0

Я пробовал следовать. Он работает на скрипке. Но не работает с html. Imgae загружается, но не изменяет его размер при обжиге.Изменение размера изображения на Html

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<script> 
 
var current_h = $('img').height(); 
 
var current_w = $('img').width(); 
 

 
     $('.resize').hover(
 
     function() { 
 
      $(this).stop(true, false).animate({ 
 
       width: (current_w * 3.15), 
 
       height: (current_h * 3.15) 
 
      }, 300); 
 
     }, function() { 
 
      $(this).stop(true, false).animate({ 
 
       width: current_w + 'px', 
 
       height: current_h + 'px' 
 
      }, 300); 
 
     }); 
 
</script> 
 
</head> 
 
<body> 
 
<div class="box"> 
 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250"/> 
 
</div> 
 
</body> 
 
</html>

Любой вопрос здесь?

+0

Попробуйте обертывание вашу функцию в '$ (документ) .ready()' – Pugazh

+0

я не вижу причины, почему ответы ниже должны быть отмечены вниз? Все они указывают на один очень простой факт, что ОП пытался ссылаться на то, чего не было. –

+0

Я отметил один, у которого была инициализация вне функции. Теперь он исправлен. У другого не было объяснений. – mplungjan

ответ

3

Вы должны выполнить OnLoad - ваш код выполняется до того, как изображение существует:

$(function() { // when the page has loaded 
 
    var current_h = $('img').height(); 
 
    var current_w = $('img').width(); 
 

 
    $('.resize').hover(
 
    function() { 
 
     $(this).stop(true, false).animate({ 
 
     width: (current_w * 3.15), 
 
     height: (current_h * 3.15) 
 
     }, 300); 
 
    }, function() { 
 
     $(this).stop(true, false).animate({ 
 
     width: current_w + 'px', 
 
     height: current_h + 'px' 
 
     }, 300); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<div class="box"> 
 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" /> 
 
</div>

Если у вас есть более одного изображения, вы можете сохранить размер изображения в данном IMG в attribute - я также добавил высоту к тегу изображения.

$(function() { // when the page has loaded 
 
    $(".box img").each(function() { 
 
    $(this).data("w",$(this).width()); 
 
    $(this).data("h",$(this).height()); 
 
    }); 
 
    $('.resize').hover(
 
    function() { 
 
     $(this).stop(true, false).animate({ 
 
     width: ($(this).data("w") * 3.15), 
 
     height: ($(this).data("h") * 3.15) 
 
     }, 300); 
 
    }, function() { 
 
     $(this).stop(true, false).animate({ 
 
     width: $(this).data("w") + 'px', 
 
     height: $(this).data("h") + 'px' 
 
     }, 300); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<div class="box"> 
 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" height="250" /> 
 
</div><div class="box"> 
 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" height="250" /> 
 
</div>

+0

Я пробовал это. Хорошо работает в IE, но в Chrome иногда он работает, но большую часть времени он «сжимает» изображение и исчезает. –

+0

Это неверно, если вы делаете это правильно, начальный текущий размер необходимо принять после загрузки изображения. Ваш код предполагает одно изображение на странице. У меня нет проблем с моим кодом в хром. – mplungjan

+0

Посмотрите на измененный пример.Я сохраняю размер изображения в атрибуте данных и добавляет высоту в тег изображения тоже – mplungjan

1

Попробуйте обертывание вашу функцию в $(document).ready(). Потому что ваш код работает до загрузки изображения.

Ниже приведен рабочий пример

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
    <script> 
 
    $(document).ready(function() { 
 
     var current_h = $('img').height(); 
 
     var current_w = $('img').width(); 
 
     $('.resize').hover(
 
     function() { 
 
      $(this).stop(true, false).animate({ 
 
      width: (current_w * 3.15), 
 
      height: (current_h * 3.15) 
 
      }, 300); 
 
     }, function() { 
 
      $(this).stop(true, false).animate({ 
 
      width: current_w + 'px', 
 
      height: current_h + 'px' 
 
      }, 300); 
 
     }); 
 
    }); 
 
    </script> 
 
</head> 
 

 
<body> 
 
    <div class="box"> 
 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" /> 
 
    </div> 
 
</body> 
 

 
</html>

+1

@mplungjan: Спасибо. Обновлен ответ! – Pugazh

+0

Которая теперь идентична моей, включая комментарий – mplungjan

+0

Я пробовал это. Хорошо работает в IE, но в Chrome иногда он работает, но большую часть времени он «сжимает» изображение и исчезает. –

1

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<script> 
 
    
 
    $(document).ready(function(){ 
 
     var current_h = $('img').height(); 
 
var current_w = $('img').width(); 
 

 
     $('.resize').hover(
 
     function() { 
 
      $(this).stop(true, false).animate({ 
 
       width: (current_w * 3.15), 
 
       height: (current_h * 3.15) 
 
      }, 300); 
 
     }, function() { 
 
      $(this).stop(true, false).animate({ 
 
       width: current_w + 'px', 
 
       height: current_h + 'px' 
 
      }, 300); 
 
     }); 
 
    
 
    }); 
 
</script> 
 
</head> 
 
<body> 
 
<div class="box"> 
 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250"/> 
 
</div> 
 
</body> 
 
</html>

1

Попробуйте ниже

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ // Note this line 
var current_h = $('img').height(); 
var current_w = $('img').width(); 

     $('.resize').hover(
     function() { 
      $(this).stop(true, false).animate({ 
       width: (current_w * 3.15), 
       height: (current_h * 3.15) 
      }, 300); 
     }, function() { 
      $(this).stop(true, false).animate({ 
       width: current_w + 'px', 
       height: current_h + 'px' 
      }, 300); 
     }); 
     }); // note that the additional line ends here 
</script> 
</head> 
<body> 
<div class="box"> 
    <img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250"/> 
</div> 
</body> 
</html> 

Также смотрите Jquery документацию по $ (документ) .ready

1

Изменить этот

img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" 

в

img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" class="resize" width="250" height="250" 

Я думаю, что это будет решать ваши проблемы.

Благодаря

Смежные вопросы