Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除/替换动态创建的<;风格>;标记(使用jQuery)_Jquery_Css_Dynamic - Fatal编程技术网

删除/替换动态创建的<;风格>;标记(使用jQuery)

删除/替换动态创建的<;风格>;标记(使用jQuery),jquery,css,dynamic,Jquery,Css,Dynamic,我正在使用一种常见的技术从JavaScript/jQuery中创建s,就像这样 $('<style>.tilewidth { width:' + tilesize + 'px; height: ' + tilesize + 'px;}</style>').appendTo('head'); function addStyle(sname,scode) { scode = "." + sname + " {" + scode + "}"; if ($("#styl

我正在使用一种常见的技术从JavaScript/jQuery中创建
s,就像这样

$('<style>.tilewidth { width:' + tilesize + 'px; height: ' + tilesize + 'px;}</style>').appendTo('head');
function addStyle(sname,scode) {
  scode = "." + sname + " {" + scode + "}";
  if ($("#style-" + sname).length)
    $("#style-" + sname).html(scode);
  else
    $("<style/>").attr("id","style-"+sname).html(scode).appendTo("head");
}

这很有效-谢谢!:)

给你的
样式
添加一个
id
标签并移除它?例如

$('#sizing').remove();
$('<style id="sizing">…</style>').appendTo('head');
$(“#调整大小”).remove();
$(“…”).appendTo('head');
实际上,再想一想,你最好只是设置文本,而不是一遍又一遍地创建一个元素

var sizing = $('#sizing');
if (sizing.length) {
  sizing.text('my new styles');
} else {
  $('<style id="sizing">…</style>').appendTo('head');
}
var size=$('#size');
if(尺寸、长度){
文本(“我的新样式”);
}否则{
$(“…”).appendTo('head');
}

这根本不是一种常见的技术,最好直接在元素上设置样式:

$('.tilewidth').css({
                     width:  tilesize+'px',
                     height: tilesize+'px'
                   });

这样,元素样式将在调整大小时更新,而不是添加一堆样式标记。

那么,当文档中有20多个元素使用相同的样式时,情况如何?:)不要紧,如果他们有相同的类,样式将被应用。jQuery的
css()
函数可以处理数百万个元素,只要你能正确地定位它们。。。您并不是说“设置类”tilewidth的宽度为tilewidthpx,而是说“设置所有元素的类”tilewidth的宽度为该宽度。类实际上只是一个标签,而不是有实际内容的东西,这是解决问题的一种倒退方式。但这是可行的course@JohnPeat-我明白你的意思,但这是数十亿网站的做法,也是所有库的做法,只需将样式附加到内部样式表中即可,但出于某种原因,普通javascript和库(如mootools和jQuery)都决定这样做。现在你该怎么做取决于你自己,我当然觉得内部样式表比内联样式更吸引人,但我现在只会坚持按常规方式来做。@JohnPeat-奇怪的是,这个问题刚刚出现…好主意-我把它改编成了一个函数,以便轻松使用(见编辑问题)