【发布时间】:2016-07-09 06:21:14
【问题描述】:
所以我已经玩了大约一个小时,并且一直在通过 stackoverflow 进行搜索。我只是想根据窗口大小调整将这个图像设置为屏幕中心以保持在中心。我发现了类似的东西,除了它可能会在一段时间后失去对屏幕中心的跟踪并偏离中心。下面是我正在使用的代码。
HTML
<img data-target="#csgo1" class="csgo img" align="middle" src="https://upload.wikimedia.org/wikipedia/en/6/6f/Smiley_Face.png"
<center><img data-target="#csgo1" style="display:none;" id="csgo1" class="csgo1 img" align="middle" src="pictures/csgo.png"></center>
CSS
.img
{
cursor:pointer;
}
.csgo1
{
opacity:.35;
-webkit-filter: brightness(70%);
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
margin:0 auto;
border-left: 75px;
border-right: 75px;
border-top:10px;
border-bottom:10px;
border-color:#0a1b0a;
border-style:solid;
left:40%;
top:100px;
position:fixed;
z-index:100;
transition: 1s ease;
}
.csgo1:hover
{
opacity:1;
-webkit-filter: brightness(100%);
-webkit-transform: scale(1.05);
-ms-transform: scale(1.05);
transform: scale(1.05);
transition: 1s ease;
}
jQuery
//function to set image in center of screen
$(document).ready(function(){
$('.img').on('click', function(){
var target = $($(this).data('target'));
if(target.css('display') == "none"){
target.attr('src',$(this).attr('src'));
$(".content").animate({opacity: .1});
$(".footer").animate({opacity: .1});
target.attr('style', 'height:' + this.height*2 + 'px;');
target.attr('style', 'width:' + this.width*2 + 'px;');
target.css("top", Math.max(0, (($(window).height() - target.outerHeight()) / 2)) + "px");
target.css("left", Math.max(0, (($(window).width() - target.outerWidth()) / 2)) + "px");
test = true;
target.fadeIn();
}else{
target.hide();
test = false
$(".content").animate({opacity: 1}, 10);
$(".footer").animate({opacity: 1}, 10);
}
});
});
//function to resize image on window resize
$(window).resize(function() {
var curWidth = $(window).width(); //store the window's current width
var curHeight = $(window).height();
var delta = (curWidth- origWidth);
var charlie = (curHeight- origHeight);
$(".csgo1").offset({left:($(".csgo1").offset().left + delta)});
$(".csgo1").offset({top:($(".csgo1").offset().top + charlie)});
origWidth = curWidth;
origHeight = curHeight;
});
https://jsfiddle.net/nathanahartmann/dqjua4dk/
任何有关如何在不丢失窗口中心的情况下获得更居中图片的帮助将不胜感激!
这是我正在努力解决此问题的实际网站。 nathanahartmann.com
使用文本对齐:居中; 和顶部:计算(50%);左:计算(50%); 如下所列,我的所有图像都没有正确居中。对此的任何帮助将不胜感激。
【问题讨论】:
-
P.S:
<center>标签早已被弃用。请改用 CSStext-align: center。 -
text-align: center会为您解决问题,但在水平轴上。它的垂直居中需要额外的逻辑。你可以follow the tutorials here。 -
我的整个身体以margin为中心:0 auto;这仍然会产生尴尬的结果,因为某些图像仍然偏心,以至于这不起作用,而
只是试图解决这个问题。我已经把它拿出来了,忘了从这个例子中删除它。 -
您是否还想在滚动时保持居中(两个轴)??
标签: jquery html css image center