本文實例講述了js取得及修改網頁背景色和字體色的方法。分享給大家參考,具體如下:
取得網頁的背景色和字體顏色,方法如下:
思想: 透過取得顏色屬性值得到的是 rgb 色,不是我們想要的,所以需要將 rgb 色裝換為 十六進位色 ,先得到rgb色 :
程式碼如下:
for(var k = 0; k < 3; k++){ str[k] = parseInt(rgb .split(',')[k]).toString(16);//str 数组保存拆分后的数据 }
程式碼如下:
<!DOCTYPE html> <html> <head> <title>getHexColor js/jQuery 获得十六进制颜色</title> <meta charset="utf-8" /> <script type="text/javascript"> function getHexBgColor(){ var str = []; var rgb = document.getElementById('color').style.backgroundColor.split('('); for(var k = 0; k < 3; k++){ str[k] = parseInt(rgb[1].split(',')[k]).toString(16); } str = '#'+str[0]+str[1]+str[2]; document.getElementById('color').innerHTML = str; } function getHexColor(){ var str = []; var rgb = document.getElementById('color').style.color.split('('); for(var k = 0; k < 3; k++){ str[k] = parseInt(rgb[1].split(',')[k]).toString(16); } str = '#'+str[0]+str[1]+str[2]; document.getElementById('color').innerHTML = str; } </script> <style type="text/css"> #color{ width: 200px; height: 200px; line-height: 200px; text-align: center; } </style> </head> <body> <div style="color: #88ee22; background-color: #ef8989;" id="color"></div> <input onclick="getHexBgColor();" type="button" value="获得背景色" /> <input onclick="getHexColor();" type="button" value="获得字体颜色" /> </body> </html>
<body leftmargin=5 topmargin=0 onmouseover="document_onmouseover();"onclick="document_onclick();" id="all" > <SCRIPT LANGUAGE="javascript"> var curObj= null; var curObjmouseover=null; function document_onclick() { if(window.event.srcElement.tagName=='A'||window.event.srcElement.tagName=='FONT'){ if(curObjmouseover!=null) curObjmouseover.style.background=''; if(curObj!=null) curObj.style.background=''; curObj=window.event.srcElement; curObj.style.background='#ff0099'; } } function document_onmouseover() { if(window.event.srcElement.tagName=='A'||window.event.srcElement.tagName=='FONT'){ if(curObjmouseover!=null) {curObjmouseover.style.background=''; curObjmouseover.style.color='#000000';} if(curObj!=null) curObj.style.background=''; curObjmouseover=window.event.srcElement; curObjmouseover.style.background='#cccc00'; curObjmouseover.style.color='#ffffff'; } } </SCRIPT> <div> <a href='#'>来自脚本之家</a> </div> <div> <a href='#'>来自脚本之家</a> </div>