2013-04-13 46 views
1

我試圖在單擊時創建div contentEditable,然後在mouseout上將contentEditable設置爲false,但迄今爲止我還沒有成功。點擊一個鏈接出現,突出它,否則什麼事情都不:在點擊時切換contentEditable

http://jsfiddle.net/GeVpe/19/

<div id="content" contentEditable="true" onclick = "this.contentEditable = true;" onmouseout = "this.contentEditable = false;"> 
    Surprisingly, <a href="http://google.com">clicking this link does nothing at all.</a> How can I fix this problem? 
</div> 

我預想的鏈接帶我去的鏈接頁面,當它被點擊,而是有人強調,當點擊並沒有做任何事情。我該如何解決這個問題?

+0

事實證明,鏈接無法正常工作,即使它不是一個CONTENTEDITABLE DIV中。我想我已經找到了原因:http://stackoverflow.com/questions/15994328/clicking-a-link-has-no-effect-at-all –

+0

安德森格林是正確的 - 這是因爲jsFiddle使用iFrames。另外一個使用類的通用解決方案在這裏:http://jsfiddle.net/dirkk0/8CNyw/ – dirkk0

回答

3

永遠不要使用內聯html腳本聲明,這是一個不好的做法。我認爲你的鏈接沒有做任何事情的原因是,當你爲你的div設置它時,事件監聽器冒泡/傳播並更改它的默認onclick事件。

我建議你做這樣的事情。

 window.onload = function() { 
      var div = document.getElementById('editable'); 
      div.onclick = function(e) { 
       this.contentEditable = true; 
       this.focus(); 
       this.style.backgroundColor = '#E0E0E0'; 
       this.style.border = '1px dotted black'; 
      } 

      div.onmouseout = function() { 
       this.style.backgroundColor = '#ffffff'; 
       this.style.border = ''; 
       this.contentEditable = false; 
      } 
     } 

     // And for HTML 

     <div id="content"> 
      <span id='editable'>Surprisingly,</span> 
      <a href="http://google.com">clicking this link does nothing at all.</a> 
     </div> 
+0

你怎麼知道內聯腳本聲明被認爲是不好的做法? –

+0

你測試了這個腳本嗎?我試着運行它,仍然有像以前一樣的問題:http://jsfiddle.net/GeVpe/20/ –

+0

這是不好的混合JavaScript與HTML,當你可以做一個更好的方式,我猜你可以用它進行一些簡單的操作,但最終你會發現它對你來說還不夠。如果你谷歌這個問題,你會發現很多關於它的文章。 是的,我在發佈之前嘗試了腳本。它在你的jsfiddle測試中也不適用於我。我不知道爲什麼。嘗試在jsfiddle之外進行測試。只需將它放在一個html文件中並在瀏覽器中運行即可。對我來說工作得很好。 –

0

嘗試將目標設定爲blank

<div id="content" contentEditable="true" onclick = "this.contentEditable = true;" onmouseout = "this.contentEditable = false;"> 
    Surprisingly, <a href="http://google.com" target = "blank">clicking this link does nothing at all.</a> How can I fix this problem? 
</div> 
1
Here we can make html element editable true and false using this code. 

    $("#mylabel").click(function() { 
// we get current value of html element 
     var value = $('#editablediv').attr('contenteditable'); 
//if its false then it make editable true 
    if (value == 'false') { 
     $('#editablediv').attr('contenteditable','true'); 
    } 
    else { 
//if its true then it make editable false 
     $('#editablediv').attr('contenteditable','false'); 
    } 
    }); 
+0

圍繞代碼更好地[添加更多的上下文/解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)(相對於只有代碼的答案)因爲這使答案更有用。 – EJoshuaS

+0

感謝您的評論,我添加了內容。 –