CSS : img : hover에서 이미지 src 변경
에서 <img>
소스 URL 을 변경해야합니다 hover
.
나는 이것을 시도했지만 작동하지 않습니다.
HTML
<img id="my-img" src="http://dummyimage.com/100x100/000/fff"/>
CSS
#my-img:hover {
content: url('http://dummyimage.com/100x100/eb00eb/fff');
}
어떤 도움을 주시면 감사하겠습니다.
최신 정보:
이것은 Webkit / Google Chrome에서만 작동합니다.
html과 css만으로는 이미지의 src를 변경할 수 없습니다. img 태그를 div 태그로 바꾸면 배경으로 설정된 이미지를 다음과 같이 변경할 수 있습니다.
div {
background: url('http://dummyimage.com/100x100/000/fff');
}
div:hover {
background: url('http://dummyimage.com/100x100/eb00eb/fff');
}
그리고 일부 자바 스크립트 코드를 사용할 수 있다고 생각하면 아래와 같이 img 태그의 src를 변경할 수 있습니다.
function hover(element) {
element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');
}
function unhover(element) {
element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');
}
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
Patrick Kostjens와 관련된 몇 가지 변경 사항을 수정했습니다.
<a href="#">
<img src="http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png"
onmouseover="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/red-bird-icon.png'"
onmouseout="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png'"
border="0" alt=""/></a>
데모
http://jsfiddle.net/ssuryar/wcmHu/429/
당신이 할 수있는 일은 실제 이미지를 숨기고 원하는 것을하기 위해 CSS를 적용하기 위해 설정 width
하고 height
0 으로 설정하여 약간의 속임수를 쓰는 것입니다 .
#aks {
width:0px;
height:0px;
background:url('http://dummyimage.com/100x100/000/fff');
padding:50px;
}
#aks:hover {
background: url('http://dummyimage.com/100x100/eb00eb/fff');
}
그리고 img
태그를 원하는 크기로 만드는 패딩 (실제 이미지 크기의 절반).
비슷한 문제가 있었지만 내 해결책은 두 개의 이미지, 하나는 숨겨져 있고 하나는 표시되는 것입니다. 주변 범위 위로 마우스를 가져 가면 원본 이미지가 display : none으로 변경되고 다른 이미지는 display : block으로 변경됩니다. (상황에 따라 대신 '인라인'을 사용할 수 있음)
이 예제에서는 이미지 대신 두 개의 span 태그를 사용하므로 여기에서 실행할 때 결과를 볼 수 있습니다. 불행히도 사용할 온라인 이미지 소스가 없었습니다.
#onhover {
display: none;
}
#surround:hover span[id="initial"] {
display: none;
}
#surround:hover span[id="onhover"] {
display: block;
}
<span id="surround">
<span id="initial">original</span>
<span id="onhover">replacement</span>
</span>
다음은 순수 CSS를 사용하는 다른 접근 방식입니다. 아이디어는 HTML 마크 업에 두 이미지를 포함하고 이에 따라 표시되거나 숨겨지는 것입니다. : hover
HTML
<a>
<img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_15-128.png" />
<img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_12-128.png" />
</a>
CSS
a img:last-child {
display: none;
}
a:hover img:last-child {
display: block;
}
a:hover img:first-child {
display: none;
}
jsfiddle : https://jsfiddle.net/m4v1onyL/
사용 된 이미지는 적절한 표시를 위해 동일한 크기입니다. 또한 이러한 이미지 파일 크기는 매우 작기 때문에 여러 개를로드하는 것은이 경우 문제가되지 않지만 큰 크기의 이미지 표시를 전환하려는 경우 발생할 수 있습니다.
해결책이 하나 더 있습니다. AngularJs를 사용하는 사람이 있다면 : http://jsfiddle.net/ec9gn/30/
<div ng-controller='ctrl'>
<img ng-mouseover="img='eb00eb'" ng-mouseleave="img='000'"
ng-src='http://dummyimage.com/100x100/{{img}}/fff' />
</div>
자바 스크립트 :
function ctrl($scope){
$scope.img= '000';
}
CSS 없음 ^^.
src
CSS로 변경할 수 없으므로 jQuery가 옵션 인 경우이 바이올린을 확인하십시오.
데모
$('#aks').hover(
function(){
$(this).attr('src','http://dummyimage.com/100x100/eb00eb/fff')
},
function(){
$(this).attr('src','http://dummyimage.com/100x100/000/fff')
}
)
기본적으로 .hover()
방법을 사용하고 있습니다. 작동하려면 두 가지 기능이 필요합니다. 호버를 입력하고 종료 할 때.
우리는 사용 .attr
의 변화에 (속성에 대한 짧은) src
속성을.
이 작업을 수행하려면 바이올린과 같이 jQuery 라이브러리가 포함되어 있어야합니다.
비슷한 문제가 있습니다. : hover에서 그림을 바꾸고 싶지만 Bootstrap의 적응 형 디자인이 부족하여 BACKGRUND-IMAGE를 사용할 수 없습니다.
나를 좋아한다면 : hover (특정 이미지 태그에 대한 변경 SRC를 고집하지 않음)에서만 그림을 변경하려면 다음과 같이 할 수 있습니다-CSS 전용 솔루션입니다.
HTML :
<li>
<img src="/picts/doctors/SmallGray/Zharkova_smallgrey.jpg">
<img class="hoverPhoto" src="/picts/doctors/Small/Zharkova_small.jpg">
</li>
CSS :
li { position: relative; overflow: hidden; }
li img.hoverPhoto {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
opacity: 0;
}
li.hover img { /* it's optional - for nicer transition effect */
opacity: 0;
-web-kit-transition: opacity 1s ease;
-moz-transition: opacity 1s ease;li
-o-transition: opacity 1s ease;
transition: opacity 1s ease;
}
li.hover img.hoverPhoto { opacity: 1; }
IE7 호환 코드를 원하면 불투명도가 아닌 위치를 지정하여 : HOVER 이미지를 숨기거나 표시 할 수 있습니다.
AshisKumar의 답변에 동의
하면 아래와 같이 jQuery 기능을 사용하여 마우스 오버시 이미지 URL을 변경하는 방법이 있습니다.
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
$(this).attr("src", url1); //URL @the time of mouse over on image
})
.mouseout(function() {
var src = $(this).attr("src").replace("over", "");
$(this).attr("src", url2); //default URL
});
});
개인적으로 JavaScript / jQuery 솔루션 중 하나를 사용합니다. 이렇게하면 HTML 의미가 유지 될뿐만 아니라 (즉, 이미지가 마크 업에 정의 된 일반적인 src 이미지와 함께 img 요소로 표시됨) JS / jQuery 솔루션을 사용하는 경우 JS / hover 이미지 를 미리로드하는 jQuery .
마우스 오버 이미지를 미리로드하면 사용자가 원본 이미지 위로 마우스를 가져갈 때 다운로드 지연이 없을 가능성이 높아 사이트가 훨씬 더 전문적으로 작동합니다.
그것은 당신이 JS에 의존한다는 것을 의미하지만, JS가 활성화되지 않은 소수는 아마도 너무 소란스럽지 않을 것입니다. 그리고 다른 모든 사람들은 더 나은 경험을 얻을 것입니다 ... 그리고 당신의 코드도 좋을 것입니다!
을 사용하여 img
태그의 src
속성을 변경할 수 없습니다 CSS
. 자바 스크립트 onmouseover()
이벤트 핸들러를 사용하여 가능 합니다.
HTML :
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover='hover()'/>
자바 스크립트 :
function hover() {
document.getElementById("my-img").src = "http://dummyimage.com/100x100/eb00eb/fff";
}
css를 사용하여 img src를 변경할 수 없습니다. 그래도 다음과 같은 순수한 CSS 솔루션을 사용할 수 있습니다. HTML :
<div id="asks"></div>
CSS :
#asks {
width: 100px;
height: 100px;
background-image: url('http://dummyimage.com/100x100/0000/fff');
}
#asks:hover {
background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
또는 배경 이미지와 함께 div를 사용하지 않으려면 javascript / jQuery 솔루션을 사용할 수 있습니다. HTML :
<img id="asks" src="http://dummyimage.com/100x100/000/fff" />
jQuery :
$('#asks')
.mouseenter(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/eb00eb/fff');})
.mouseleave(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/000/fff');});
이를 위해 아래 코드를 사용할 수 있습니다.
1) HTML
<div id = "aks">
</div>
2) CSS
#aks
{
width:100px;
height:100px;
background-image:url('http://dummyimage.com/100x100/000/fff');}
#aks:hover {
background-image:url('http://dummyimage.com/100x100/eb00eb/fff');
}
이전 브라우저에서는 요소 :hover
에서만 작동했습니다 <a>
. 따라서 작동하도록하려면 이와 같은 작업을 수행해야합니다.
<style>
a#aks
{
width:100px;
height:100px;
display:block;
}
a#aks:link
{
background-image: url('http://dummyimage.com/100x100/000/fff');
}
a#aks:hover
{
background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
</style>
<a href="#" id="aks"></a>
다음 코드는 Chrome과 Firefox 모두에서 작동합니다.
<a href="#"><img src="me-more-smile.jpg" onmouseover="this.src='me-thinking-about-a-date.jpg'" onmouseout="this.src='me-more-smile.jpg'" border="0" alt=""/></a>
의미론과 관련하여 지금까지 제공된 솔루션이 마음에 들지 않습니다. 따라서 개인적으로 다음 솔루션을 사용합니다.
.img-wrapper {
display: inline-block;
background-image: url(https://www.w3schools.com/w3images/fjords.jpg);
}
.img-wrapper > img {
vertical-align: top;
}
.img-wrapper > img:hover {
opacity: 0;
}
<div class="img-wrapper">
<img src="https://www.w3schools.com/w3css/img_lights.jpg" alt="image" />
</div>
This is a CSS only solution with good browser compatibility. It makes use of an image wrapper that has a background which is initially hidden by the image itself. On hover, the image is hidden through the opacity, hence the background image becomes visible. This way, one does not have an empty wrapper but a real image in the markup code.
Heres a pure CSS solution. Put the visible image in the img tag, put the second image as a background in the css, then hide the image on hover.
.buttons{
width:90%;
margin-left:5%;
margin-right:5%;
margin-top:2%;
}
.buttons ul{}
.buttons ul li{
display:inline-block;
width:22%;
margin:1%;
position:relative;
}
.buttons ul li a p{
position:absolute;
top:40%;
text-align:center;
}
.but1{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but1 a:hover img{
visibility:hidden;
}
.but2{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but2 a:hover img{
visibility:hidden;
}
.but3{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but3 a:hover img{
visibility:hidden;
}
.but4{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but4 a:hover img{
visibility:hidden;
}
<div class='buttons'>
<ul>
<li class='but1'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Blog</p></a></li>
<li class='but2'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /> <p>Herrero</p></a></li>
<li class='but3'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Loftin</p></a></li>
<li class='but4'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Contact</p></a></li>
</ul>
</div>
The best way to change src
for image is:
<img src='willbehidden.png' style="width:0px; height:0px; padding: 8px; background: url(newimage.png);">
See live demo: http://www.audenaerde.org/csstricks.html#imagereplacecss
Enjoy!
Try This Code.
.card {
width: 200px;
height: 195px;
position: relative;
display: inline-block;
}
.card .img-top {
display: none;
position: absolute;
top: 0;
left: 0;
z-index: 99;
width:200px;
}
.card:hover .img-top {
display: inline;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Change on Hover with CSS</title>
</head>
<body>
<div class="card">
<img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">
<img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">
</div>
</body>
</html>
참고URL : https://stackoverflow.com/questions/18032220/css-change-image-src-on-imghover
'program story' 카테고리의 다른 글
JavaScript window.location에 target =“_ blank”를 추가하는 방법은 무엇입니까? (0) | 2020.08.21 |
---|---|
UIView와 CALayer의 차이점은 무엇입니까? (0) | 2020.08.21 |
오류 : 요청 헤더 필드 Content-Type은 Access-Control-Allow-Headers에서 허용되지 않습니다. (0) | 2020.08.21 |
정규식은 물음표 뒤의 모든 항목과 일치합니까? (0) | 2020.08.21 |
LESS CSS 중첩 클래스 (0) | 2020.08.21 |