gpt4 book ai didi

JavaScript 和 CSS 为任何分辨率定位图像

转载 作者:行者123 更新时间:2023-11-30 10:19:51 24 4
gpt4 key购买 nike

我正在尝试创建在背景 div 中设置的图像的简单幻灯片放映。我在创建幻灯片代码时没有问题,但我在定位图像时遇到问题,该图像应根据其他显示器分辨率的宽度而改变。

在我描述的下面的图像中,我想放置图像。图像应放在红色的 div 中。

enter image description here

这是我想放在红色 div 中的图像,就像背景一样。分辨率为 (1900px x 500px)

enter image description here

这是我设法做到的模型。我尝试在 java 脚本代码中声明一个全局变量 sw 我分配了 window.innerWidth (sw=window.innerWidth),之后CSS 使用 jquery 选择红色 div $('#rotator') 并分配 sw ($('#rotator').css('width', sw)), 但结果不是我需要获得的。我获得了根据屏幕分辨率从右侧裁剪的图像。 enter image description here

如果有人知道如何解决这个问题,我将不胜感激!

这是我的代码:

HTML

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" src="function.js"></script>
<script src="jquery.easing.1.3.js"></script>
</head>
<body >
<div id="rotator"></div>
<div class='slider'></div>
</body>
</html>

CSS

body{
margin: 0px;
margin-left: 0px;
}

.slider{
width: 940px;
height: 360px;
background-color: #FFDF00;
margin: 0 auto;
position: absolute;
left: 15%;
top: 20px;
}

#rotator {
position: relative;
height: 500px;
}

.puzzle {
width: 100px;
height: 100px;
background-position: -100px 0px;
float: left;
}

并且JavaScript也包含幻灯片效果的功能(可以工作)。

$(document).ready(init)

sw=window.innerWidth;

if (sw % 100 == 0) {
sw=window.innerWidth
}
else{
sw=Math.floor(sw/100)*100
}


//counter of slider
current_slide=0;
image_list=new Array
(
"img/1.jpg",
"img/2.jpg",
"img/3.jpg",
"img/4.jpg",
"img/5.jpg"
);

function init ()
{
$('#rotator').css('width', sw)
change(image_list[current_slide]);
//start timer
setInterval( "change(image_list[current_slide])" ,2500);
}

function change(bg_image){
// this function creats cells inside <div id = 'rotator'>
rot = $('#rotator'); //constructor
rot.empty();
for(y = 1; y<=5; y++)
{
for(x = 1; x<=sw/100; x++)
{
rot.append('<div class = "puzzle p-' + x + '-' + y + ' "></div>');
//select the <div> using his class and setting up the cells coordinates
$('.p-' + x + '-' + y).css('background-position', (-(x-1)*100) + 'px ' + (- (y-1)*100) + 'px').css('background-image','url('+bg_image+')');
$('.p-' + x + '-' + y).css('opacity', 0).delay(parseInt(Math.random()*1000)).animate({opacity: 1}, {duration: 1000})
}
}
current_slide++;
if(current_slide >= image_list.length)current_slide=0
}

感谢您的时间和考虑!

最佳答案

要么将图像放入宽度随页面大小动态变化的容器 div 中,并将其中图像的宽度设置为 100%,要么使用 CSS 属性 background-size: cover; (仅与较新的浏览器兼容)。

除非使用 background-size: cover;,否则设置为 div 背景图像的图像将简单地填充其容器并在其缩小超过背景图像的尺寸时被该容器裁剪。为了在旧版浏览器中获得相同的效果,使用了上述 100% 技巧。

跨浏览器风格: http://jsfiddle.net/2D5Vw/

新(大概)-学校: http://jsfiddle.net/HLf2Q/

关于JavaScript 和 CSS 为任何分辨率定位图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21888807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com