admin管理员组

文章数量:1420120

This should be fairly simple. All I need to do is pass a new block of parameters to my body css tag webkit gradient with a javascript function that gets called from a link. Here's what I tried (among 200 other things):

CSS

body
{
    -webkit-text-size-adjust:100%;
    font-size:100%;
    color:#444;
    position:relative;
    background: -webkit-linear-gradient(top, #154d9e, #b8d8e4);
}

Javascript

<script>
function changeBack()
{
    document.getElementsByTagName("body").style.background="-webkit-linear-gradient(top, #fff, #000)";
    document.body.style.background="-webkit-linear-gradient(top, #fff, #000)";
}
</script>

Neither of those two lines work. What gives?

This should be fairly simple. All I need to do is pass a new block of parameters to my body css tag webkit gradient with a javascript function that gets called from a link. Here's what I tried (among 200 other things):

CSS

body
{
    -webkit-text-size-adjust:100%;
    font-size:100%;
    color:#444;
    position:relative;
    background: -webkit-linear-gradient(top, #154d9e, #b8d8e4);
}

Javascript

<script>
function changeBack()
{
    document.getElementsByTagName("body").style.background="-webkit-linear-gradient(top, #fff, #000)";
    document.body.style.background="-webkit-linear-gradient(top, #fff, #000)";
}
</script>

Neither of those two lines work. What gives?

Share Improve this question asked Apr 14, 2013 at 11:29 David HaririDavid Hariri 1941 gold badge3 silver badges15 bronze badges 1
  • This example may help -- click on "Position" and you can change the gradient with the slider. – Lars Kotthoff Commented Apr 14, 2013 at 11:33
Add a ment  | 

2 Answers 2

Reset to default 3

This doesn't work because document.getElementsByTagName("body") returns an array of elements. You need to specify which element it is. There is only one body tag on a page so this should work:

document.getElementsByTagName("body")[0].style.background="-webkit-linear-gradient(top, #fff, #000)";

I had the same problem and I success with use linear-Gradient unless -webkit. You can replace rgb colors by Hexadecimal format (ex. #F767676).

 document.body.style.background = "linear-gradient(90deg, rgb(0, 255, 0), rgb(0, 0, 255))";

Here is a working fiddle example.

https://jsfiddle/cdgpts9n/

本文标签: htmlModify background webkitgradient with javascriptStack Overflow