开发者

JavaScript - Changing style when none exists

开发者 https://www.devze.com 2023-01-13 05:59 出处:网络
I have a function which wanders through the elements in a page 开发者_StackOverflow中文版and adjusts the font size

I have a function which wanders through the elements in a page 开发者_StackOverflow中文版and adjusts the font size

function changebuttonsize (sz)
{
  var z = document.body.getElementsByTagName("*");  
  for (var i=0; i<z.length; i++)
  {
    if (z[i].id=="BTSz")
    {
      z[i].style.fontSize = sz;
    }
  }
}

I use it to change the size of the following buttons

<input id="BTSz" type="button" style="font-size:16px;" value="Back"  onclick="history.go(-1);"/>
<input id="BTSz" type="button" style="font-size:16px;" value="Index" onclick="location.href='Index.html';"/>
<input id="BTSz" type="button" style="font-size:16px;" value="Home"  onclick="location.href='Introduction.html';"/>

The problem is that I had to include a style clause in the button definition or the change did not take effect. Is there some way to correct this? Do I somehow have to create a style area for the element?


Using the same value for the "id" attribute of several elements is a recipe for all sorts of weirdness. I'm not sure it'd cause whatever problems you're having, but while fooling around looking for a solution it'd be a good idea to fix that.

Usually, the "class" attribute is used to store this sort of "trait" values. You can also use a "data-" attribute if you're coding for HTML5:

<input type='button' data-MikeD='BtNSz' ... >

and then use getAttribute to fetch the value:

  var value = theButton.getAttribute("data-MikeD");


How about this?

function changebuttonsize (sz)
{
  var z = document.body.getElementsByTagName("*");  
  for (var i=0; i<z.length; i++)
  {
    if (z[i].id=="BTSz")
    {
      z[i].style = 'font-size:'+sz+'px';
    }
  }
}


Have you ever considered using jQuery? Using jQuery you are able to select specific items (using selectors) in the DOM and add a class to anything.

0

精彩评论

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