[英]Selecting/Highlighting Rows AND Changing Value of Highlighted Text Field in the Same Row
[英]Highlighting table rows and changing text color
我想通過更改背景顏色和文本顏色來突出顯示表格中的行。 更改背景顏色工作正常,但文本顏色不正常。 我的代碼有什么問題,文字顏色不會改變onClick?
的script.js
var preEl ;
var BColor;
var TColor;
function highlight(el){ // funkcia pre zvyraznenie riadkov
if(typeof(preEl)!='undefined') {
preEl.text=TColor;
preEl.bgColor=BColor;
}
TColor = el.text;
el.text = '#FF0000';
BColor = el.bgColor;
el.bgColor = '#FF3333';
preEl = el;
}
表
<table>
<tr onClick="highlight(this);" >
<td>Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>
<td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
<td>1</td>
<td>F138</td>
<td>Klik pre detaily</td>
</tr>
</table>
嘗試這個
var preEl ;
var BColor;
var TColor;
function highlight(el){ // funkcia pre zvyraznenie riadkov
if(typeof(preEl)!='undefined') {
preEl.style.color = TColor;
preEl.style.backgroundColor = BColor;
}
TColor = el.style.color;
el.style.color = '#FF0000';
BColor = el.style.backgroundColor;
el.style.backgroundColor = '#FF3333';
preEl = el;
}
這一行:
el.text
應該
el.style.color
但我建議改為轉換類名。 它會使代碼更清晰:
function highlight(el) { // funkcia pre zvyraznenie riadkov
el.className = el.className === 'selected' ? '' : 'selected'
}
CSS:
.selected {
background-color: #FF3333;
color: #FF0000;
}
要一次只允許選擇一行:
function highlight(e) {
if (selected[0]) selected[0].className = '';
e.target.parentNode.className = 'selected';
}
var table = document.getElementById('table'),
selected = table.getElementsByClassName('selected');
table.onclick = highlight;
嘗試其他的東西。 使用css和事件委托 。
在css中創建一個類:
tr.highlighted {
background: #FF3333;
color: #FFF000; /* #FF0000 is almost the background color */
}
在你的js文件中創建一個監聽器函數:
function highlight(e){
e = e || event;
var from = findrow(e.target || e.srcElement)
,highlighted = from ? /highlighted/i.test(from.className) : false;
if (from)
from.className = !highlighted ? 'highlighted' : '';
}
// findrow: find parent tr tag of the clicked Element
function findrow(el){
if (/tr/i.test(el.tagName))
return el;
var elx;
while (elx = el.parentNode) {
if (/tr/i.test(elx.tagName)) {
return elx;
}
}
return null;
}
最后為表元素分配一個單擊處理程序:
document.querySelector('table').onclick = highlight;
看到這個jsFiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.