活动介绍
file-type

JavaScript操作:动态改变元素背景与类名

5星 · 超过95%的资源 | 下载需积分: 33 | 652KB | 更新于2025-07-20 | 101 浏览量 | 29 下载量 举报 收藏
download 立即下载
在讨论JavaScript(简称js)如何改变背景图像(backgroundImage)和类名称(class)之前,需要了解几个关键的Web开发概念:DOM操作、CSS样式的动态应用以及类的操作。 ### DOM操作 文档对象模型(Document Object Model,简称DOM)是Web开发中非常核心的技术。它定义了访问和操作文档(比如HTML页面)的接口。当我们在JavaScript中想要改变页面的元素,无论是样式、类名称还是其他属性,我们实际上是在操作DOM树上的节点。 ### 改变背景图像(backgroundImage) 在JavaScript中,我们可以使用`document.getElementById`、`document.querySelector`等方法获取到目标元素的DOM对象。一旦我们有了这个对象,我们就可以访问或修改它的样式属性,比如背景图像。 ```javascript // 获取DOM对象 var element = document.getElementById('elementId'); // 直接设置backgroundImage属性 element.style.backgroundImage = "url('new-image.jpg')"; // 或者使用CSS类 element.className = "new-class"; ``` 使用`backgroundImage`属性的好处是简单直接,但缺点是不如使用CSS类那样易于管理,也不容易适应不同的媒体查询或是响应式设计。 ### 改变类名称(class) 改变元素的类名称是Web开发中常见的需求,尤其是当我们想要应用不同的样式集或是响应用户交互时。通过JavaScript,我们可以将类添加到元素上,也可以移除它们。这通常通过`classList`属性来实现,它提供了`add`、`remove`和`toggle`等方法。 ```javascript // 获取DOM对象 var element = document.getElementById('elementId'); // 添加一个类 element.classList.add('new-class'); // 移除一个类 element.classList.remove('old-class'); // 切换一个类的开关状态 element.classList.toggle('toggle-class'); ``` ### JavaScript与CSS的配合 尽管可以直接在JavaScript中修改样式属性,但最佳实践是尽可能使用CSS来管理样式。这意味着通过JavaScript修改类名称,然后在CSS文件中定义这些类的具体样式。 ```css /* 在CSS文件中 */ .new-class { background-image: url('new-image.jpg'); /* 其他样式 */ } ``` 通过这种方式,我们可以保持样式和行为的分离,这有助于维护和扩展应用程序。 ### 实际应用 当需要根据用户交互或程序逻辑改变页面元素的背景图像或类名称时,可以使用事件监听器来响应各种事件,比如点击、鼠标悬停等。 ```javascript // 通过点击事件改变样式 element.addEventListener('click', function() { this.classList.toggle('highlight'); }); ``` ### 注意事项 - 当使用JavaScript改变背景图像或类名称时,要确保元素ID或类选择器的正确性,否则无法选中目标元素。 - 直接在JavaScript中设置样式(如`backgroundImage`属性)可能导致样式难以维护,特别是在大型项目中。始终优先考虑使用CSS类。 - 在多浏览器环境下测试JavaScript代码,确保功能的兼容性。 ### 结语 综上所述,通过JavaScript我们可以非常灵活地操作DOM元素的背景图像和类名称,为Web页面带来丰富的交互体验。但需要注意的是,这样的操作应该基于清晰和可维护的代码结构之上,以确保Web应用的长期可维护性。

相关推荐

filetype

<template>
{{ section.name }}
<a-empty description="暂无分类" />
<a-form :model="searchForm" label-align="left" auto-label-width layout="inline" :size="'large'" class="search-header" ref="searchHeaderRef"> <a-form-item style="width: 320px;" field="base_title" label="能力名称:" size="large"> <a-input allow-clear v-model="searchForm.base_title" placeholder="搜索能力..." @press-enter="fetchTableData" @clear="resetSearch"> <template #prefix> <icon-search /> </template> </a-input> </a-form-item> <a-form-item> <a-space size='large'> <a-button type="primary" size="medium" @click="fetchTableData"> <template #icon><icon-search /></template>查询 </a-button> <a-button type="outline" size="medium" @click="resetSearch"> <template #icon><icon-refresh /></template>重置 </a-button> </a-space> </a-form-item> </a-form> <a-spin :loading="loading" style="width: 100%">
<icon-apps /> {{ section.name }}
<template v-for="(subSection, subIndex) in section.children" :key="subIndex">
{{ subSection.name }}
能力背景
能力图标
<a-image width="100" height="100" src="some-error.png" />
{{ item.title }}
{{ item.description }}
</template>
<a-empty description="暂无能力数据" />
</a-spin>
</template> <script setup lang="ts"> import { ref, onMounted, nextTick, reactive } from 'vue'; import { IconSearch, IconApps, IconRefresh } from '@arco-design/web-vue/es/icon'; import { Message } from '@arco-design/web-vue'; import { useAbilityMallStore } from '@/store/modules/ability-mall'; import { storeToRefs } from 'pinia'; import { useRouter } from 'vue-router'; import { getAbilityMallList, getabilityMallDetails, createAbilityMall, } from '@/api/abilityMall'; const abilityMallStore = useAbilityMallStore(); const { abilityMallList, abilityMallDetails } = storeToRefs(abilityMallStore); const { getabilityMallDetailsStore } = abilityMallStore; const router = useRouter(); // 定义三级分类数据结构 interface CategoryItem { id: string; title: string; description: string; image: string; } interface SubCategory { id: string; name: string; children: CategoryItem[]; } interface MainCategory { id: string; name: string; children: SubCategory[]; } // 状态管理 const sections = ref<MainCategory[]>([]); const sectionContainerRef = ref<HTMLElement | null>(null); const searchHeaderRef = ref<HTMLElement | null>(null); // 添加搜索表单引用 const sectionRefs = ref<HTMLElement[]>([]); const activeIndex = ref(0); const loading = ref(false); const headerHeight = ref(0); const searchForm = reactive({ base_title: '', }); // 更高效的数据转换函数 const transformData = (apiData: any[]): MainCategory[] => { const categoryMap = new Map<string, MainCategory>(); const subcategoryMap = new Map<string, SubCategory>(); apiData.forEach((item) => { const categoryName = item.base_category; const categoryId = categoryName.replace(/\s+/g, '-').toLowerCase(); // 处理一级分类 if (!categoryMap.has(categoryId)) { categoryMap.set(categoryId, { id: categoryId, name: categoryName, children: [], }); } const category = categoryMap.get(categoryId)!; // 处理二级分类 const subcategoryName = item.base_subcategory; const subcategoryId = `${categoryId}-${subcategoryName .replace(/\s+/g, '-') .toLowerCase()}`; if (!subcategoryMap.has(subcategoryId)) { const subcategory: SubCategory = { id: subcategoryId, name: subcategoryName, children: [], }; subcategoryMap.set(subcategoryId, subcategory); category.children.push(subcategory); } const subcategory = subcategoryMap.get(subcategoryId)!; // 添加三级分类项 subcategory.children.push({ id: item.id, title: item.base_title, description: item.base_content, image: item.base_image, // 添加图片字段 }); }); return Array.from(categoryMap.values()); }; // 设置章节引用 const setSectionRef = (el: any) => { if (el) { sectionRefs.value.push(el); } }; // 获取搜索表单高度 const getSearchHeaderHeight = (): number => { return searchHeaderRef.value?.offsetHeight || 80; }; // 滚动到指定章节 - 修复滚动位置计算 const scrollToSection = (index: number) => { if (!sectionContainerRef.value || index < 0 || index >= sectionRefs.value.length) return; activeIndex.value = index; const targetSection = sectionRefs.value[index]; const headerHeight = getSearchHeaderHeight(); // 精确计算滚动位置:目标位置 - 顶部间距 + 容器滚动位置 const targetOffset = targetSection.offsetTop - headerHeight; sectionContainerRef.value.scrollTo({ top: targetOffset, behavior: 'smooth', }); }; // 初始化滚动监听 const initScrollListener = () => { if (!sectionContainerRef.value) return; // 初始计算一次搜索表单高度 headerHeight.value = getSearchHeaderHeight(); }; // 处理滚动事件 - 修复滚动位置判断逻辑 const handleScroll = () => { if (!sectionContainerRef.value || sectionRefs.value.length === 0) return; const scrollTop = sectionContainerRef.value.scrollTop; const containerHeight = sectionContainerRef.value.clientHeight; const headerHeight = getSearchHeaderHeight(); // 计算有效滚动位置(考虑搜索表单高度) const effectiveScrollTop = scrollTop + headerHeight; // 1. 处理滚动到底部的情况 if (scrollTop + containerHeight >= sectionContainerRef.value.scrollHeight - 10) { activeIndex.value = sectionRefs.value.length - 1; return; } // 2. 精确计算当前激活的section let currentIndex = 0; let closestDistance = Number.MAX_VALUE; // 找到距离顶部最近的section for (let i = 0; i < sectionRefs.value.length; i++) { const section = sectionRefs.value[i]; const distance = Math.abs(section.offsetTop - effectiveScrollTop); if (distance < closestDistance) { closestDistance = distance; currentIndex = i; } } // 3. 处理最后两个section的特殊情况 if (sectionRefs.value.length > 1) { const lastSection = sectionRefs.value[sectionRefs.value.length - 1]; const secondLastSection = sectionRefs.value[sectionRefs.value.length - 2]; // 当滚动位置接近最后两个section时 if (effectiveScrollTop >= secondLastSection.offsetTop - 50) { // 如果已经滚动到最后一个section if (effectiveScrollTop >= lastSection.offsetTop - headerHeight) { currentIndex = sectionRefs.value.length - 1; } else { currentIndex = sectionRefs.value.length - 2; } } } // 只有当索引变化时才更新 if (activeIndex.value !== currentIndex) { activeIndex.value = currentIndex; } }; // 重置搜索 const resetSearch = () => { searchForm.base_title = ''; fetchTableData(); }; // 获取数据 async function fetchTableData() { loading.value = true; try { const { data } = await getAbilityMallList(searchForm); const fakeData = data.filter((item) => item.deleted === 0); sections.value = transformData(fakeData || []); // 重置引用 nextTick(() => { sectionRefs.value = []; // 初始化滚动监听 setTimeout(() => { initScrollListener(); handleScroll(); // 初始计算一次激活状态 // 添加初始滚动位置修正 if (sections.value.length > 0) { scrollToSection(0); } }, 100); }); } catch (error) { console.error('获取能力模型失败:', error); Message.error('获取能力模型失败'); } finally { loading.value = false; } } // 跳转详情 const sceneDetail = async (item: CategoryItem) => { loading.value = true; await getabilityMallDetailsStore(item.id); router.push({ name: 'AbilityDetails', query: { id: item.id }, }); loading.value = false; }; // 生命周期钩子 onMounted(() => { fetchTableData(); }); </script> <style scoped> .container { display: flex; height: 100vh; position: relative; padding: 0; background: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } /* 左侧导航栏样式 */ .tabs { width: 200px; padding: 20px 0; flex-shrink: 0; position: sticky; top: 0; max-height: 100vh; overflow-y: auto; z-index: 10; background: #f9fafb; border-right: 1px solid #e5e6eb; .tabs-wrapper { padding: 0 10px; } .tab { height: 44px; line-height: 44px; text-align: center; margin: 8px 0; font-size: 15px; color: #1d2129; cursor: pointer; position: relative; transition: all 0.3s ease; border-radius: 6px; overflow: hidden; font-weight: 500; &:hover { background: #f2f3f5; color: #3261CE; transform: translateX(3px); } } .tab.active { color: #3261CE; background: #e8f3ff; font-weight: 600; box-shadow: 0 1px 4px rgba(22, 93, 255, 0.15); &::before { content: ''; position: absolute; left: 0; top: 0; height: 100%; width: 3px; background: #3261CE; } } .empty-container { padding: 40px 20px; } } /* 右侧内容区域 */ .content { flex: 1; height: 100%; position: relative; padding: 0; overflow: hidden; display: flex; flex-direction: column; } /* 搜索头部样式 */ .search-header { width: 100%; display: flex; gap: 16px; padding: 15px 24px; background: #fff; border-bottom: 1px solid #e5e6eb; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03); position: sticky; top: 0; z-index: 20; .header-title { font-size: 20px; font-weight: 600; margin-right: 20px; color: #1d2129; } } /* 分类区域样式 - 关键修改 */ .section-container { flex: 1; overflow-y: auto; scroll-behavior: smooth; padding: 0 24px; position: relative; height: calc(100vh - 80px); /* 减去搜索栏高度 */ } .section { padding: 32px 0; border-bottom: 1px solid #e5e6eb; &:first-child { padding-top: 24px; } &:last-child { border-bottom: none; } } .section-title { font-size: 22px; color: #1d2129; padding-bottom: 16px; margin-bottom: 16px; border-bottom: 1px solid #e5e6eb; font-weight: 600; display: flex; align-items: center; .arco-icon { margin-right: 10px; color: #3261CE; font-size: 20px; } } .title { font-size: 18px; color: #3261CE; margin: 24px 0 16px; padding-left: 12px; border-left: 4px solid #3261CE; font-weight: 500; } /* 内容项网格布局 */ .sub-content { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 20px; margin-top: 8px; } /* 内容项样式 */ .content-item { position: relative; height: 95px; cursor: pointer; border-radius: 8px; overflow: hidden; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.03); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); background: #fff; border: 1px solid #e5e6eb; /* 背景图片容器 */ .img-wrapper { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; opacity: 0; transform: scale(1.05); transition: all 0.5s cubic-bezier(0.22, 0.61, 0.36, 1); img { width: 100%; height: 100%; object-fit: cover; filter: blur(0); transition: filter 0.5s ease; } } /* 悬停效果 */ &:hover { transform: translateY(-5px); box-shadow: 0 12px 25px rgba(22, 93, 255, 0.2); border-color: rgba(22, 93, 255, 0.3); .img-wrapper { opacity: 1; transform: scale(1); img { filter: blur(4px) brightness(0.9); } } .item { background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(4px); } .item-image img { transform: scale(1.8); } } } /* 内容卡片样式 */ .item { display: flex; position: relative; overflow: hidden; border-radius: 8px; width: 100%; height: 100%; z-index: 2; background: rgba(255, 255, 255, 0.95); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); } /* 图片样式 */ .item-image { width: 100px; height: 100%; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; background: #f7f8fa; transition: background 0.3s ease; img { width: 60px; height: 60px; object-fit: contain; display: block; transition: transform 0.5s cubic-bezier(0.22, 0.61, 0.36, 1); } .image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: #c9cdd4; .arco-icon { font-size: 32px; } } } /* 文本区域样式 */ .item-text { flex: 1; padding: 16px 12px; display: flex; flex-direction: column; justify-content: center; overflow: hidden; } .item-title { font-size: 16px; color: #1d2129; font-weight: 500; margin-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: color 0.3s ease; } .item-desc { font-size: 13px; color: #86909c; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; line-height: 1.5; transition: color 0.3s ease; } /* 响应式调整 */ @media (max-width: 992px) { .container { flex-direction: column; } .tabs { width: 100%; position: sticky; top: 0; z-index: 30; display: flex; overflow-x: auto; padding: 10px 0; height: auto; border-right: none; border-bottom: 1px solid #e5e6eb; .tabs-wrapper { display: flex; padding: 0 16px; } .tab { flex-shrink: 0; margin: 0 8px; padding: 0 16px; height: 36px; line-height: 36px; } } .content { margin-left: 0; } .search-header { padding: 12px 16px; flex-wrap: wrap; } .section-container { padding: 0 16px; height: calc(100vh - 140px); /* 调整移动端高度 */ } .section { padding: 24px 0; } } @media (max-width: 576px) { .sub-content { grid-template-columns: 1fr; } .header-title { display: none; } .search-header { :deep(.arco-form-item) { width: 100%; margin-bottom: 12px; } } .section-container { height: calc(100vh - 180px); /* 调整小屏幕高度 */ } .content-item { height: 110px; } .item-image { width: 80px; } } </style>在这个代码基础上修改