开发者

can't find the bug help! rgb to hex in js

    //right window "bakgrundsfärg
    function readingFrontValues_right(){

//getting the values from the textboxes
    var text1 = parseInt(document.getElementById("backred").value);
    var hex1 = text1.toString(16);
    var text2 = parseInt(document.getElementById("backgreen").value);
    var hex2 = text2.toString(16);
    var text3 = parseInt(document.getElementById("backblue").value);
    var hex3 = text3.toString(16);
    //presenting the result
      var checkingHexa_2 = "#";
    checkingHexa_2 += hex1;
    checkingHexa_2 += hex2;
    checkingHexa_2 += hex3;
    var setText_2 = document.getElementById(("backgroundcolorhex"));
          开发者_如何学编程//setting the hexvalue in the last-textbox
    setText_2.value = checkingHexa_2;
    //var backColor = document.getElementById("colorslab");
      //  backColor.style.backgroundColor = checkingHexa_2;
    setBgColorById("colorslab", checkingHexa_2);
        alert(checkingHexa_2);
   //  var bgcolor = document.getElementById("colorslab");
   //  bgcolor.style.backgroundColor = checkingHexa_2;
   // addingResult(checkingHexa);
}

function setBgColorById(id,sColor) {
 var elem;
 if (document.getElementById) {
  if (elem = document.getElementById(id)) {
   if (elem.style) {
    elem.style.backgroundColor=sColor;
    return 1;  // success
   }
  }
 }
 return 0;  // failure
}


You should specify 10 as the base when applying parseInt on the rgb decimal, and you must pad any one character hex values to 2 places.

A will become '0A', 0 will be '00', 9 will be '09' and so on.


Your code will return 4 and 5 character hex codes which are invalid for use as HTML colour codes.

Why not use something like this? (snaffled from here)

function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
 n = parseInt(n,10);
 if (isNaN(n)) return "00";
 n = Math.max(0,Math.min(n,255));
 return "0123456789ABCDEF".charAt((n-n%16)/16)
      + "0123456789ABCDEF".charAt(n%16);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜