2017-05-19 30 views
0

我有兩個圖像使用例如rose.jpg和mary.jpg。一旦我點擊rose.jpg,我需要彈出mary.jpg。我想在這裏使用模態。如果流行圖像與要點擊的圖像相同,我知道該怎麼做,但在這種情況下,我的大圖像的名稱完全不同。我已經看到了多個其他的例子,它們描述了彈出式窗口或窗體,但點擊圖像時本身並不是圖像。 以下是我迄今爲止所做的。它僅適用於相同的圖像:如何使用javascript打開完全不同圖像的彈出圖像?

<html> 
<head> 
<style> 
#myImg { 
    border-radius: 5px; 
    cursor: pointer; 
    transition: 0.3s; 
} 

#myImg:hover {opacity: 0.7;} 

.modal { 
    display: none; 
    position: fixed; 
    z-index: 1; /* Sit on top */ 
    padding-top: 100px; /* Location of the box */ 
    left: 0; 
    top: 0; 
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgb(0,0,0); 
    background-color: rgba(0,0,0,0.9); 
} 

/* Modal Content (image) */ 
.modal-content { 
    margin: auto; 
    display: block; 
    width: 80%; 
    max-width: 700px; 
} 
#caption { 
    margin: auto; 
    display: block; 
    width: 80%; 
    max-width: 700px; 
    text-align: center; 
    color: #ccc; 
    padding: 10px 0; 
    height: 150px; 
} 


.close { 
    position: absolute; 
    top: 15px; 
    right: 35px; 
    color: #f1f1f1; 
    font-size: 40px; 
    font-weight: bold; 
    transition: 0.3s; 
} 
.close:hover, 
.close:focus { 
    color: #bbb; 
    text-decoration: none; 
    cursor: pointer; 
} 
</style> 
</head> 
<body> 
<img id="myImg" src="rose.jpg" alt="flower" > 


<div id="myModal" class="modal"> 
    <span class="close">&times;</span> 
    <img class="modal-content" src="mary.jpg" alt="mary" id="img01"> 
    <div id="caption"></div> 
</div> 
<script> 
var modal = document.getElementById('myModal'); 

var img = document.getElementById('myImg'); 
var modalImg = document.getElementById("img01"); 
var captionText = document.getElementById("caption"); 
img.onclick = function(){ 
    modal.style.display = "block"; 
    modalImg.src = this.src; 
    captionText.innerHTML = this.alt; 
} 
var span = document.getElementsByClassName("close")[0]; 

span.onclick = function() { 
    modal.style.display = "none"; 
} 
</script> 
</body> 
</html> 

在這個例子中modalImg.src = this.src;是它是獲得原始圖像,而不是流行的其他圖像的了。我需要顯示我給出的源碼爲<img class="modal-content" src="mary.jpg" alt="mary" id="img01">的mary.jpg。請幫忙。

回答

0

在你onclick功能,您作爲平等的設置IMG srcthis.src

img.onclick = function(){ 
    modal.style.display = "block"; 
    modalImg.src = this.src; 
    captionText.innerHTML = this.alt; 
} 

通過這樣做,在這種情況下使用,每次點擊圖片您在IMG SRC設置爲rose.jpg

如果刪除modalImg.src = this.src;那麼你應該模式只是簡單的「開放」,通過顯示blockonclick,並顯示你的HTML,它已經定義了IMG SRC。

<div id="myModal" class="modal"> 
    <span class="close">&times;</span> 
    <img class="modal-content" src="mary.jpg" alt="mary" id="img01"> 
    <div id="caption"></div> 
</div>