jQuery动态加载CSS文件的多种方法_jquery
在jQuery 中动态加载 CSS 文件有多种方法,以下是几种常用实现方式:
// 动态加载外部 CSS 文件function loadCSS(url) { $('', { rel: 'stylesheet', type: 'text/css', href: url }).appendTo('head');}// 使用示例loadCSS('https://example.com/style.css');
// 直接注入 CSS 代码(适合小文件或动态样式)$.get('path/to/your.css', function(css) { $('').appendTo('head');});
// 带成功/失败回调的 CSS 加载function loadCSS(url, success, error) { const link = $('', { rel: 'stylesheet', href: url }).appendTo('head'); // 检测加载状态(注意:部分浏览器不支持 link.onload) link[0].onload = function() { success && success() }; link[0].onerror = function() { error && error() };}// 使用示例loadCSS('theme.css', () => console.log('CSS 加载成功!'), () => console.error('CSS 加载失败!'));
// 存储主题 URLconst themes = { dark: 'css/dark-theme.css', light: 'css/light-theme.css'};// 切换主题函数function switchTheme(themeName) { // 移除旧主题 $('link[data-theme]').remove(); // 添加新主题 $('', { rel: 'stylesheet', 'data-theme': themeName, href: themes[themeName] }).appendTo('head');}// 使用示例$('#btn-dark').click(() => switchTheme('dark'));$('#btn-light').click(() => switchTheme('light'));
function loadCSS(url, id) { // 检查是否已存在 if ($('link#' + id).length) return; $('', { id: id, rel: 'stylesheet', href: url }).appendTo('head');}// 使用loadCSS('popup.css', 'popup-styles');
根据需求选择合适的方法,通常方法 1 是最简单且符合标准的方式。
到此这篇关于jQuery动态加载CSS文件的多种方法的文章就介绍到这了,更多相关jQuery动态加载CSS内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
本文地址: https://www.earthnavs.com/jishuwz/0410ccccbfec68d9d8d1.html




















