몇 개의 이미지와 그 롤오버 이미지가 있습니다. jQuery를 사용하여 마우스 이동/마우스 아웃 이벤트가 발생할 때 롤오버 이미지를 표시/숨기고 싶습니다. 내 모든 이미지 이름은 다음과 같이 동일한 패턴을 따릅니다:
원본 이미지: 이미지.gif
롤오버 이미지:
Imageover.gif
마우스 오버 및 마우스 아웃 이벤트에서 이미지 소스의 &&&&&&&&&&&&&&& 부분을 각각 삽입하고 제거하고 싶습니다.
jQuery를 사용하면 어떻게 할 수 있나요?
준비 상태로 설정합니다:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("over.gif", ".gif");
$(this).attr("src", src);
});
});
URL 이미지 소스를 사용하는 경우:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src");
var regex = /_normal.svg/gi;
src = this.src.replace(regex,'_rollover.svg');
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src");
var regex = /_rollover.svg/gi;
src = this.src.replace(regex,'_normal.svg');
$(this).attr("src", src);
});
});
jQuery 사용에 대해 질문하신 것으로 알고 있지만 자바스크립트가 꺼져 있는 브라우저에서도 CSS를 사용하여 동일한 효과를 얻을 수 있습니다:
#element {
width: 100px; /* width of image */
height: 200px; /* height of image */
background-image: url(/path/to/image.jpg);
}
#element:hover {
background-image: url(/path/to/other_image.jpg);
}
더 자세한 설명은 여기에 있습니다.
그러나 스프라이트를 사용하는 것이 더 좋습니다: simple-css-이미지-롤오버.
두 개 이상 있는 경우에는 그 이미지 및 뭐 필요한거라도 일반 doesn& # 39, t 명명 규칙을 따라 달라집니다.
HTML
<img data-other-src="big-zebra.jpg" src="small-cat.jpg">
<img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
<img data-other-src="friendly-bear.jpg" src="penguin.jpg">
JavaScript
$('img').bind('mouseenter mouseleave', function() {
$(this).attr({
src: $(this).attr('data-other-src')
, 'data-other-src': $(this).attr('src')
})
});
HTML
<img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />
JavaScript
function swap(newImg){
this.src = newImg;
}
설정에 따라, 아마 이 같은 일이 더 노력할 (및 적게 HTML 수정).
HTML
<img src="img1.jpg" id="ref1" />
<img src="img3.jpg" id="ref2" />
<img src="img5.jpg" id="ref3" />
자바스크립트 / jQuery
// Declare Arrays
imgList = new Array();
imgList["ref1"] = new Array();
imgList["ref2"] = new Array();
imgList["ref3"] = new Array();
//Set values for each mouse state
imgList["ref1"]["out"] = "img1.jpg";
imgList["ref1"]["over"] = "img2.jpg";
imgList["ref2"]["out"] = "img3.jpg";
imgList["ref2"]["over"] = "img4.jpg";
imgList["ref3"]["out"] = "img5.jpg";
imgList["ref3"]["over"] = "img6.jpg";
//Add the swapping functions
$("img").mouseover(function(){
$(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
}
$("img").mouseout(function(){
$(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
}
$('img.over').each(function(){
var t=$(this);
var src1= t.attr('src'); // initial src
var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
t.hover(function(){
$(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
}, function(){
$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
});
});
첫 번째 줄에서 이미지 클래스를 변경할 수 있습니다. 더 많은 이미지 클래스(또는 다른 경로)가 필요한 경우 다음을 사용할 수 있습니다.
$('img.over, #container img, img.anotherOver').each(function(){
등을 사용할 수 있습니다.
작동할 거예요, 테스트는 안 해봤지만 :)
만약 이 솔루션을 찾고 캐비닛용입니다 애니메이션된 버튼을 클릭한 다음, CSS 는 성능 개선을 할 수 있는 최상의 조합을 스프라이트를. 모든 이미지를 sprite 막대한 이미지 확장자입니다 사이트에서 (헤더입니다 로고, 단추, 모든 훈장을 있습니다). 있습니다 http 요청, 각 이미지를 사용하는 HTTP 요청을 로드하기에 더 많은 시간을 더 걸릴 전망이다.
.buttonClass {
width: 25px;
height: 25px;
background: url(Sprite.gif) -40px -500px;
}
.buttonClass:hover {
width: 25px;
height: 25px;
background: url(Sprite.gif) -40px -525px;
}
0px 0px '이' 에서 왼쪽 상단 모서리 스프라이트를 위치좌표 될 것입니다.
그러나 일부 사진 앨범을 개발할 경우 아약스 또는 뭐 그런 다음 JavaScript (또는 임의의 레임워크) 는 최고라니까요
이따봐
$('img').mouseover(function(){
var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
$(this).attr("src", newSrc);
});
$('img').mouseout(function(){
var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
$(this).attr("src", newSrc);
});
반면 솔루션을 찾고, 몇 시간 후 다시 찾았다고 유사물 스크립트입니다 아래 있는 일부 면변형을 나는 attaboy working for me.
이 두 이미지 처리, 거의 항상 있는 것이 기본 마우스 꺼졌기 " off", 이미지 (image-example_off.jpg), 그리고 가끔 "; 시간이 필요한 대체 어디서 on" 마우스가 맴돌고, 이미지 (image-example_on.jpg) 가 표시됩니다.
<script type="text/javascript">
$(document).ready(function() {
$("img", this).hover(swapImageIn, swapImageOut);
function swapImageIn(e) {
this.src = this.src.replace("_off", "_on");
}
function swapImageOut (e) {
this.src = this.src.replace("_on", "_off");
}
});
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JQuery</title>
<script src="jquery.js" type="text/javascript"> </script>
<style type="text/css">
#box{
width: 68px;
height: 27px;
background: url(images/home1.gif);
cursor: pointer;
}
</style>
<script type="text/javascript">
$(function(){
$('#box').hover( function(){
$('#box').css('background', 'url(images/home2.gif)');
});
$('#box').mouseout( function(){
$('#box').css('background', 'url(images/home1.gif)');
});
});
</script>
</head>
<body>
<div id="box" onclick="location.href='index.php';"></div>
</body>
</html>
이 경우, 예를 들어, 두 번째 파일을 사용할 수 있습니다 '라는 _hover 파스부k.프영' 와 'facebook_hover.png'
$('#social').find('a').hover(function() {
var target = $(this).find('img').attr('src');
//console.log(target);
var newTarg = target.replace('.png', '_hover.png');
$(this).find('img').attr("src", newTarg);
}, function() {
var target = $(this).find('img').attr('src');
var newTarg = target.replace('_hover.png', '.png');
$(this).find('img').attr("src", newTarg);
});
<img src="img1.jpg" data-swap="img2.jpg"/>
img = {
init: function() {
$('img').on('mouseover', img.swap);
$('img').on('mouseover', img.swap);
},
swap: function() {
var tmp = $(this).data('swap');
$(this).attr('data-swap', $(this).attr('src'));
$(this).attr('str', tmp);
}
}
img.init();
Ul / 수명*을 타겟으로의 오버클로킹된 img 의 목록 (여기를 통해 com/downloads/global/corporate/iar/esg_prosupport. 래퍼 div class), 이 같은 일이.
$('div.navlist li').bind('mouseenter mouseleave', function() {
$(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'),
'data-alt-src':$(this).find('img').attr('src') }
);