2016-01-23 91 views
0

我是新來的發展,所以這可能是一個簡單的答案。我想弄清楚如何在焦點/活動時更改整個div的邊框顏色。我能夠改變文本框的邊界,但似乎是我能找到的唯一答案。 任何幫助表示讚賞。 謝謝!如何在聚焦時更改整個div的邊框顏色?

回答

1

在你的CSS文件..

div:focus { 
    border: 1px solid black; 
} 

div:active { 
    border: 1px solid black; 
} 

你可以改變 '黑' 到你喜歡的任何顏色。

+0

謝謝!我不需要在JavaScript上使用焦點嗎? – turnt84

0

CSS版本

div:focus { 
    border: 1px solid black; 
} 

div:active { 
    border: 1px solid black; 
} 

Javascript版本

//doSomething is the name of the function to get fired 
    document.getElementById("myDiv").addEventListener("focus", doSomething); 

//whatIsActive will return the element type that is active at the moment 
    var whatIsActive = document.activeElement; 

http://www.w3schools.com/jsref/prop_document_activeelement.asp

雖然兩者都是有效的,我只想建議的JavaScript方法,如果您正在發生變化比其他東西div的外觀。

---編輯爲下面的評論---

FOCUS

//listens for focus on textbox 
document.getElementById('myTextbox').addEventListener("focus", changeDivColor); 

//this is fired when the textbox is focused 
function changeDivColor(){ 
    document.getElementById('myDiv').style.borderColor = "red"; 
} 

BLUR(取消)

//listens for blur on textbox 
document.getElementById('myTextbox').addEventListener("blur", revertDivColor); 

//this is fired when the textbox is no longer focused 
function revertDivColor(){ 
    document.getElementById('myDiv').style.borderColor = "black"; 
} 

看到它在行動:https://jsfiddle.net/0h8zyhba/1/

+0

謝謝!這幾乎是我正在尋找的。點擊Div內的文本框後,如何將Div邊框保持爲已更改的顏色,然後在單擊不同的Div時更改爲默認顏色? – turnt84

+0

非常感謝!這正是我所期待的,但我無法在瀏覽器中使用它。我會繼續玩它! – turnt84

+0

你使用什麼瀏覽器? Safari,Firefox和Chrome都爲我工作。你檢查了上面的JSFiddle嗎? –