나는 5 개의 img 요소를 가지고 있는데, 각각은 ".backgroundImage"클래스를 가지고있다. 아래 스크립트는 그것을 중심으로합니다. 스크립트를 5 번이나 작성하지 않고 모든 개인 img에서 스크립트를 수행하도록 스크립트에 지시하려면 어떻게해야합니까?여러 요소에 스크립트 실행
function resize(){
var imageWidth = $('.backgroundImage').width();
var imageHeight = $('.backgroundImage').height();
var windowWidth = $(window).width();
var windowHeight = $(window).height();
if(imageWidth>windowWidth){
var newWidth = -(imageWidth - windowWidth)/2;
$('.backgroundImage').css('margin-left', newWidth);
};
if(imageHeight>windowHeight){
var newHeight = -(imageHeight - windowHeight)/2;
$('.backgroundImage').css('margin-top', newHeight);
};
};
스크립트가 말했다, 이제 변수
function resize(selector){
var imageWidth = $(selector).width();
var imageHeight = $(selector).height();
var windowWidth = $(window).width();
var windowHeight = $(window).height();
if(imageWidth>windowWidth){
var newWidth = -(imageWidth - windowWidth)/2;
$(selector).css('margin-left', newWidth);
};
if(imageHeight>windowHeight){
var newHeight = -(imageHeight - windowHeight)/2;
$(selector).css('margin-top', newHeight);
};
};
를 전달하여
['.each()'(http://api.jquery.com/ 각 /) 귀하의 [이전 질문] (http://stackoverflow.com/questions/7907799/jquery-with-several-elements-issue) –
에 대한 허용 대답에 사용 된 것과 마찬가지로 각 요소에 CSS를 적용해야합니다. 당신은 이미 그것을 코딩했습니다. @cookiemonster - .each()는 필요 없습니다. – j08691
@ j08691 : 각 요소마다 '너비/높이'가 다를 수 있습니다. 지금 그는 처음 발견 된 폭과 높이를 얻고 있습니다. –