简体   繁体   English

Javascript仅在单击时显示完整图像,否则屏幕会适合

[英]Javascript Show full image only on click otherwise fit screen

I am trying to display single image on a web page so that : 我正在尝试在网页上显示单个图像,以便:

If the image is smaller than screen of the user. 如果图像小于用户的屏幕。 Full Image is shown 显示完整图像

Otherwise if the image is larger than user's screen then it should fit screen and once image is clicked only then full size is shown . 否则,如果图像大于用户屏幕,则它应适合屏幕,并且仅单击图像后,将显示完整尺寸。

Here is my html 这是我的html

<html>
<body>
<div class="img">
<img src="imagepathhere.jpg" />
</div>

</body>
</html>

Here is the css that I have tried but I guess it is not possible by just only using css: 这是我尝试过的css,但我想仅使用css是不可能的:

    <style>
    html,body{
    min-width:100%;
    margin:0px;
    padding:0px;
    }

    .img {
    padding:0px;
    width:auto;
    text-align:center;
    margin:auto;
    }
    .img img {
    max-width:100%;
    }
</style>

What would be best way to do it? 最好的方法是什么?

Ahmar. 艾哈迈尔。

Toggle max-width:100% on click 切换max-width:100%点击时的max-width:100%

The easiest way to do this is to add this property to a class instead of applying it to the tag name 最简单的方法是将此属性添加到类中,而不是将其应用于标签名

.img .shrinkToFit {
    max-width:100%;
}

And then use JQuery to toggle it on click 然后使用JQuery在单击时进行切换

$(".img").on("click", function() {
    $(this).find("img").toggleClass("shrinkToFit");
});

Example: http://jsfiddle.net/TrevinAvery/anryho0o/ 示例: http//jsfiddle.net/TrevinAvery/anryho0o/

Here's a solution that confines the image as you described, but to it's parent div, rather than the entire screen (to make it easier to use as an example). 这是一种解决方案,可将您所描述的图像限制在其范围内,但仅限于其父div,而不是整个屏幕(以使其更易于用作示例)。 It uses the css :not() selector which may not have full browser support. 它使用css :not()选择器,该选择器可能不完全支持浏览器。

http://codepen.io/sean9999/pen/LlCJa/ http://codepen.io/sean9999/pen/LlCJa/

 "use strict"; $('#toggleimage a').on('click',function(){ $('.img img').prop('src', $(this).data('imgSrc') ); }); $('.img img').on('click',function(){ $(this).toggleClass('fullsize'); }); 
  html,body{ min-width:100%; margin:0px; padding:0px; background-color: silver; } .img { padding:0px; width: 450px; height: 450px; background-color: white; text-align:center; margin:auto; border: 1px dotted gray; } .img img:not(.fullsize) { max-width:100%; max-height: 100%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <ul id="toggleimage"> <li><a href="#" data-img-src="http://nerdhow.files.wordpress.com/2008/02/mushroombgbig.png">load big image</li> <li><a href="#" data-img-src="http://api.jquery.com/jquery-wp-content/themes/jquery/images/logo-jquery.png">load small image</a></li> </ul> <div class="img"> <img src="http://api.jquery.com/jquery-wp-content/themes/jquery/images/logo-jquery.png" /> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM