2012-11-14 20 views
0

我是新來的腳本,並花費一些時間試圖寫一些代碼。腳本來讀取圖像src

我想讀一個特定的圖像動態寫入源,然後寫一個稍微不同的源像另一個圖像在頁面上低了下去 -

此圖片是動態寫入網頁的頁面頂部

<img src="chrome.jpg" id="test1"> 

那麼低了下去,我想寫 -

<img src="chrome2.jpg"> 

會很感激這個艾米幫助。

+0

你試過了什麼? http://mattgemmell.com/2008/12/08/what-have-you-tried/ –

回答

0

承擔與「頁面」你指的是一個html頁面......我還以爲你想這樣做在客戶端...

您需要的JavaScript這一點,對於像這樣的任務使用JavaScript庫是有意義的,事情變得更容易。例如,使用jQuery庫,您可以使用「選擇器」來標識和使用dom樹元素,並添加或更改所需的所有內容。喜歡的東西:

source=$('img#test1').attr('src'); 
// do something with the source url contained now inside source 
$('p#further_down').append('<img>).attr('src',source); 

<html> 
<head> 

    <!-- inclusion of the jQuery Javascript library --> 
    <script 
    type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js 
    </script> 

    <!-- this is 'your' function --> 
    <script type="text/javascript"> 
    function doubleImg(){ 
     // you 'get' the source url of the upper image: 
     var topSrc=$('#top img').attr('src'); 
     // no you can do something with that url 
     // for this demo I replace the 'direction' inside the icons name: 
     var bottomSrc=topSrc.replace(/up/, 'down'); 
     // now you create a new <img> tag 
     // and 'set' the changed url as 'src' attribute: 
     var img=$('<img width="100">').attr('src',bottomSrc); 
     // and finally you 'add' that <img> tag into your dom tree ("the page"): 
     $('#bottom').append(img); 
    } 
    </script> 

    <!-- this gets 'your' function executed -> 
    <script type="text/javascript"> 
    $(window).load(doubleImg); 
    </script> 
</head> 

<body> 
    <!-- the "top" frame, note that it DOES hold an <img> inside --> 
    <fieldset id="top" style="border=2px solid green;"> 
    <legend>TOP</legend> 
    <img width="100" src="http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/128/Actions-arrow-up-icon.png"> 
    </fieldset> 
    <br> 
    <!-- the "bottom" frame, note that it DOES NOT hold an <img> inside --> 
    <fieldset id="bottom" style="border=2px solid blue;"> 
    <legend>BOTTOM</legend> 
    </fieldset> 
</body> 
</html> 
+0

嗨我試過這個如下但沒有運氣請幫助

user1823053

+0

嗯,我給的只是一個粗略的例子(「something _like_」)。你必須適應你的需求。永遠不要複製別人給你的東西,試着去理解它是什麼。無論如何:通常JavaScript組件保存在html頁頭內部引用的單獨文件中。你會在google上找到數以百萬計的例子,或者例如_this_頁面的源代碼。如果沒有,你必須將javascript源代碼放入html頭部_and_你必須確保它被執行。我在答案中添加了一個工作示例... – arkascha

0

我不知道你是什麼意思只有腳本的意思,所以我通過jQuery提供兩種方法可以實現你的願望的結果,通過DOM &。

  • Using jQuery:

檢索的圖像的`SRC:

var src = $(「#test1」).attr('src'); 

變化的圖像的src

$("# test1").attr("src","chrome2.jpg"); 
  • Using DOM:

檢索圖像的`源:

document.getElementById("test1").src; 

改變圖像的src

document.getElementById("test1").src="chrome2.jpg"; 

希望它能幫助。