首页 > web前端 > js教程 > 正文

如何使用 jQuery 伪克隆元素样式?

Linda Hamilton
发布: 2024-10-22 13:47:02
原创
392 人浏览过

How to Pseudo Clone Element Styles Using jQuery?

用于将元素样式克隆为伪克隆的 jQuery 插件

可以使用多种方法来创建具有不同标签的元素的伪克隆在 jQuery 中。这里有详细的解释和解决方案:

jQuery 的 getCompulatedStyle 插件

对于返回元素的计算样式对象的特定要求,您可以使用 jQuery getStyleObject 插件,它从任何元素检索所有可能的样式,包括 IE 浏览器。

用法:

var style = $("#original").getStyleObject();
登录后复制

修改 jQuery 的 CSS 方法

另一种方法是修改 jQuery 的 css 方法如下:

jQuery.fn.css2 = jQuery.fn.css;
jQuery.fn.css = function() {
    if (arguments.length) return jQuery.fn.css2.apply(this, arguments);
    var styleObj = {};
    // List of style properties to get
    var styleList = ['font-family','font-size','font-weight','font-style','color',
    'text-transform','text-decoration','letter-spacing','word-spacing',
    'line-height','text-align','vertical-align','direction','background-color',
    'background-image','background-repeat','background-position',
    'background-attachment','opacity','width','height','top','right','bottom',
    'left','margin-top','margin-right','margin-bottom','margin-left',
    'padding-top','padding-right','padding-bottom','padding-left',
    'border-top-width','border-right-width','border-bottom-width',
    'border-left-width','border-top-color','border-right-color',
    'border-bottom-color','border-left-color','border-top-style',
    'border-right-style','border-bottom-style','border-left-style','position',
    'display','visibility','z-index','overflow-x','overflow-y','white-space',
    'clip','float','clear','cursor','list-style-image','list-style-position',
    'list-style-type','marker-offset'];
    for (var i = 0; i < styleList.length; i++) {
        styleObj[styleList[i]] = jQuery.fn.css2.call(this, styleList[i]);
    }
    return styleObj;
};
登录后复制

通过此修改,您可以通过调用:

var style = $('#original').css();
登录后复制

其他编辑来获取第一个匹配元素的计算样式对象方法

对于伪克隆元素进行内联编辑的一般问题,请考虑以下替代方法:

  • jQuery.clone() 和 .replaceWith() : 克隆原始元素,将其修改为输入字段,并用克隆替换原始元素。
  • jQuery.replaceWith() 与 .data(): 替换带有输入字段的原始元素,将前一个元素的数据存储在数据属性中。编辑后,用数据替换输入。
  • ContentEditable 属性: 切换元素的 contentEditable 属性以允许直接内联编辑。

以上是如何使用 jQuery 伪克隆元素样式?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!