jQuery를 사용하여 이미지 높이를 잡습니다
문제
페이지에 많은 이미지가 있습니다. jQuery를 사용하여 각 이미지의 높이를 잡고 이미지 다음에 표시하려고합니다. 그래서 여기 내 코드가 있습니다.
$(document).ready(function() {
$(".thumb").each(function() {
imageWidth = $(".thumb img").attr("width");
$(this).after(imageWidth);
});
});
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
[...]
jQuery 뒤의 논리는 각 "썸"선택기를 통과하고 "썸"내부의 IMG 높이를 변수 "imageWidth"에 할당 한 다음 각 "엄지 손가락"이후 텍스트에 높이를 표시한다는 것입니다.
내가 가진 문제는 첫 번째 이미지에서만 작동하고 그만 두는 것입니다. 물론 "Thumb_img"클래스를 사용하면 작동 할 수 있지만 "Thumb"클래스의 이미지 높이에 액세스해야합니다.
내가 jQuery를 처음 접했기 때문에 이것은 너무 혼란스럽지 않기를 바랍니다. 감사합니다.
해결책
이것을 사용하십시오 :
imageWidth = $(this).children("img").attr("width")
다음은 모든 이미지를 선택합니다.
$(".thumb img")
... 따라서 속성을 요청하면 컬렉션의 첫 번째 개체에서 반환합니다.
모든 편집에 대해 죄송합니다 ... jQuery 객체를 재사용하는 것이 가장 좋습니다.
var $this = $(this)
그런 다음 $를 참조하십시오. 이것은 최적화에 필요했습니다. 이 예에서 큰 거래는 아니지만 사용하는 것이 좋습니다.
다른 팁
호출 당시 이미지가로드되지 않았으므로 Document.Ready ()를 사용 하여이 작업을 수행 할 수 없습니다.
실제로이 코드를 Onload () 이벤트 핸들러에 넣어야하며, 문서 후에 호출되고 모든 이미지가로드를 완료했습니다.
이미지가로드를 완료 한 경우에만 브라우저가 얼마나 큰지 알고 있습니다.
$().ready(function() {
$(".thumb img").load(function() {
var imageHeight = $(this).height();
$(this).parent().append(imageHeight);
});
});
나는 이미지를 예압하고 마우스 오버 및 마우스 아웃에 일부 코드를 설정하고 클래스 이름 "스왑"으로 모든 이미지의 스타일을 설정했습니다. 나를 위한 $(this)
일하지 않고 직접적으로 일했습니다 this
일 :
// in jquery
$(document).ready(function(){
swapAndPreload();
});
function swapAndPreload(){
$(".swap").each(function(){
// preload images in cache
var img = new Image();
img.src=this.src.replace(/([-_])out/,'$1over');
//set the hover behaviour
this.onmouseover = function(){
this.src=this.src.replace(/([-_])out/,'$1over');
}
//set the out behaviour
this.onmouseout = function(){
this.src=this.src.replace(/([-_])over/,'$1out');
}
//set the cursor style
this.style.cursor="pointer";
});
}