2012-11-05 107 views
0
<script type="text/javascript"> 
    function ToggleList(IDS) { 
     var CState = document.getElementById(IDS); 
     if (CState.style.display != "block") { CState.style.display = "block"; } 
     else { CState.style.display = "none"; } 
    } 

</script> 
<style type="text/css"> 
    .divInfo 
    { 
     display: none; 
    } 
</style> 

<p>Text</p> 
<a onclick="ToggleList('LT3')">Show More</a> 
</p> 
<div id="LT3" class="divInfo"> 
<p>Additional Test</p> 
</div> 

這很好,但是我希望當切換被展開時,標籤「顯示更多」更改爲「隱藏」。任何想法如何做到這一點? CState.innertext =「隱藏」?切換顯示/隱藏

+2

'innerText'將無法在所有的瀏覽器,並沒有將'textContent',但你可以串聯使用它們,或者使用'的innerHTML 「對所有人都有效,但這只是輕微的更多徵稅。 – TheZ

回答

3

函數中的CState對象是對DIV的引用。你應該做的是給錨點標籤一個ID,然後改變裏面的文字。然後

function ToggleList(anchorID, IDS) { 
    var CState = document.getElementById(IDS); 
    var anchor = document.getElementByID(anchorID); 

    if (CState.style.display != "block") { 
     CState.style.display = "block"; 
     anchor.innerHTML = "Hide"; 
    } else { 
     CState.style.display = "none"; 
     anchor.innerHTML = "Show more"; 
    } 
} 

你的錨標記應該是這樣的:

<a id="listToggle" onclick="ToggleList('listToggle', 'LT3')">Show More</a> 
3

爲了獲得瀏覽器的兼容性,創建一個變量是這樣的:

var text = 'textContent' in document ? 'textContent' : 'innerText'; 

然後使用它是這樣的:

CState[text] = "New Text Content"; 

但好像你想改變的標籤<a>,而不是<div>。所以,你應該這樣做,以你的HTML:

<a onclick="ToggleList(this, 'LT3')">Show More</a> 

然後給你的JS:

var text = 'textContent' in document ? 'textContent' : 'innerText'; 

function ToggleList(anchor, IDS) { 
    var CState = document.getElementById(IDS); 
    if (CState.style.display != "block") { 
     CState.style.display = "block"; 
     anchor[text] = "Hide"; 
    } else { 
     CState.style.display = "none"; 
     anchor[text] = "Show More"; 
    } 
} 

DEMO:http://jsfiddle.net/RRUEY/

1

傳遞<a>到參考功能,然後根據可見性重構該功能以重新標記它:

function ToggleList(anchor,IDS) { 
    var CState = document.getElementById(IDS); 
    var isVisible = (CState.style.display == "block"); 

    anchor.innerHTML = isVisible ? 'Show more' : 'Hide'; 
    CState.style.display = isVisible ? 'none' : 'block'; 
} 

的改變HTML:

<a onclick="ToggleList(this,'LT3')">Show More</a> 
1

我相信你會希望將ID添加到標記,例如:

<a id='txtShowMore' onclick="ToggleList('LT3')">Show More</a> 

然後讓這個腳本:

var showMoreElement = document.getElementByID('txtShowMore'); 
showMoreElement.innerHTML = "Hide"; 

當然,當你隱藏它時,將它設置回「顯示更多」也是一樣的。