display: flex;position: sticky;超出一屏后会滚上去
时间: 2025-04-20 13:34:07 浏览: 28
### 解决 CSS Flex 布局与 Sticky 定位组合使用的滚动问题
当 `display: flex` 与 `position: sticky` 组合使用时,可能会遇到一些意料之外的行为,尤其是在处理滚动条显示方面。为了确保在不同浏览器环境下的一致性和预期行为,可以采取以下方法:
#### 方法一:调整父容器的溢出属性
通过设置父级容器的 `overflow` 属性为 `auto` 而不是 `scroll-y` 可以有效防止不必要的滚动条出现[^1]。
```css
.parent-container {
display: flex;
overflow: auto; /* 使用此代替 scroll-y */
}
```
#### 方法二:确保子元素具有适当的高度约束
对于需要应用粘性定位 (`position: sticky`) 的子项来说,应该为其设定明确的最大高度或最小高度限制,从而避免因内容过少而提前触发滚动效果。
```css
.child-item {
max-height: calc(100vh - 80px); /* 根据实际需求调整数值 */
min-height: fit-content;
position: sticky;
top: 0;
}
```
#### 方法三:利用伪类优化视觉体验
为了让用户体验更加流畅自然,在定义 `.child-item` 类的同时还可以加入额外的状态样式,比如悬停状态下的背景颜色变化等,增强交互感而不影响布局逻辑。
```css
.child-item:hover {
background-color: rgba(255, 255, 255, 0.9);
}
/* 或者更具体的例子 */
.make-me-sticky {
position: relative;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
position: sticky;
top: 0;
}
```
以上措施能够帮助改善 `flexbox` 结构下 `sticky` 元素可能出现的各种滚动异常现象,提高跨平台兼容性并提供更好的用户体验。
阅读全文
相关推荐















以下修改mreditor.vue后展示完整代碼,依mrviewer.vue代碼為範例,在right-panel區塊醫案提交者的下方,顯示病態名稱的功能及樣式: mrviewer.vue範例代碼:<template> <button @click="fetchData" class="refresh-btn">刷新數據</button> <input v-model="searchQuery" placeholder="搜索..." class="search-input" /> 每頁顯示: <select v-model.number="pageSize" class="page-size-select"> <option value="1">1筆</option> <option value="4">4筆</option> <option value="10">10筆</option> </select> <button @click="prevPage" :disabled="currentPage === 1">上一页</button> 第 <input type="number" v-model.number="inputPage" min="1" :max="totalPages" class="page-input" @input="handlePageInput"> 頁 / 共 {{ totalPages }} 頁 <button @click="nextPage" :disabled="currentPage === totalPages">下一頁</button> 醫案閱讀器 0"> 醫案 #{{ (currentPage - 1) * pageSize + index + 1 }} {{ key }}: {{ formatDntagValue(value) }} ; 沒有找到匹配的數據 </template> <script> export default { name: 'mrviewer', // 必须设置组件名称用于keep-alive data() { return { api1Data: [], api2Data: [], mergedData: [], currentPage: 1, pageSize: 1, searchQuery: '', sortKey: '', sortOrders: {}, inputPage: 1, // 页码输入框绑定的值 // 字段名称映射表 fieldNames: { 'mrcase': '醫案全文', 'mrname': '醫案命名', 'mrposter': '醫案提交者', 'mrlasttime': '最後編輯時間', 'mreditnumber': '編輯次數', 'mrreadnumber': '閱讀次數', 'mrpriority': '重要性', 'dntag': '病態名稱' }, inputTimeout: null, // 用于输入防抖 dnNames: [], // 存储所有病态名称 stateVersion: '1.0' // 状态版本控制 }; }, computed: { filteredData() { const query = this.searchQuery.trim(); // 判斷是否為數字(即搜尋 ID) if (query && /^\d+$/.test(query)) { const idToSearch = parseInt(query, 10); return this.mergedData.filter(item => item.id === idToSearch); } // 一般搜索邏輯 if (!query) return this.mergedData; const lowerQuery = query.toLowerCase(); return this.mergedData.filter(item => { return Object.values(item).some(value => { if (value === null || value === undefined) return false; // 处理数组类型的值 if (Array.isArray(value)) { return value.some(subValue => { if (typeof subValue === 'object' && subValue !== null) { return JSON.stringify(subValue).toLowerCase().includes(lowerQuery); } return String(subValue).toLowerCase().includes(lowerQuery); }); } // 处理对象类型的值 if (typeof value === 'object' && value !== null) { return JSON.stringify(value).toLowerCase().includes(lowerQuery); } return String(value).toLowerCase().includes(lowerQuery); }); }); }, sortedData() { if (!this.sortKey) return this.filteredData; const order = this.sortOrders[this.sortKey] || 1; return [...this.filteredData].sort((a, b) => { const getValue = (obj) => { const val = obj[this.sortKey]; if (Array.isArray(val)) { return JSON.stringify(val); } return val; }; const aValue = getValue(a); const bValue = getValue(b); if (aValue === bValue) return 0; return aValue > bValue ? order : -order; }); }, paginatedData() { const start = (this.currentPage - 1) * Number(this.pageSize); const end = start + Number(this.pageSize); return this.sortedData.slice(start, end); }, totalPages() { return Math.ceil(this.filteredData.length / this.pageSize) || 1; } }, watch: { // 监控分页大小变化 pageSize() { // 重置到第一页 this.currentPage = 1; this.inputPage = 1; // 同步输入框的值 this.saveState(); // 保存状态 }, // 监控当前页码变化 currentPage(newVal) { // 同步输入框的值 this.inputPage = newVal; this.saveState(); // 保存状态 }, // 监控过滤数据变化 filteredData() { // 确保当前页码有效 if (this.currentPage > this.totalPages) { this.currentPage = Math.max(1, this.totalPages); } // 同步输入框的值 this.inputPage = this.currentPage; }, // 监控搜索查询变化 searchQuery() { this.saveState(); // 保存状态 } }, methods: { // 保存当前状态 saveState() { const state = { version: this.stateVersion, currentPage: this.currentPage, pageSize: this.pageSize, searchQuery: this.searchQuery, timestamp: new Date().getTime() }; sessionStorage.setItem('mrviewerState', JSON.stringify(state)); }, // 恢复状态 restoreState() { const savedState = sessionStorage.getItem('mrviewerState'); if (!savedState) return; try { const state = JSON.parse(savedState); // 检查状态版本 if (state.version !== this.stateVersion) { console.warn('状态版本不匹配,跳过恢复'); return; } // 恢复状态 this.currentPage = state.currentPage || 1; this.pageSize = state.pageSize || 1; this.searchQuery = state.searchQuery || ''; this.inputPage = this.currentPage; console.log('医案阅读器状态已恢复'); } catch (e) { console.error('状态恢复失败', e); sessionStorage.removeItem('mrviewerState'); } }, // 清除保存的状态 clearState() { sessionStorage.removeItem('mrviewerState'); }, async fetchData() { try { const api1Response = await fetch("MRInfo/?format=json"); this.api1Data = await api1Response.json(); const api2Response = await fetch("DNTag/?format=json"); this.api2Data = await api2Response.json(); // 提取所有dnname this.dnNames = this.api2Data.map(item => item.dnname).filter(name => name && name.trim()); // 按长度降序排序(确保长字符串优先匹配) this.dnNames.sort((a, b) => b.length - a.length); this.mergeData(); this.currentPage = 1; this.inputPage = 1; // 重置输入框 this.saveState(); // 保存状态 } catch (error) { console.error("獲取數據失敗:", error); alert("數據加載失敗,請稍後重試"); } }, mergeData() { this.mergedData = this.api1Data.map((item) => { const newItem = { ...item }; if (newItem.dntag && Array.isArray(newItem.dntag)) { newItem.dntag = newItem.dntag.map((tagId) => { const matchedItem = this.api2Data.find( (api2Item) => api2Item.id === tagId ); return matchedItem || { id: tagId, dnname: "未找到匹配的數據" }; }); } return newItem; }); this.sortOrders = {}; if (this.mergedData.length > 0) { Object.keys(this.mergedData[0]).forEach(key => { this.sortOrders[key] = 1; }); } }, // 处理字段名称映射 processFieldNames(item) { const result = {}; for (const key in item) { // 使用映射表转换字段名,如果没有映射则使用原字段名 const newKey = this.fieldNames[key] || key; result[newKey] = item[key]; } return result; }, // 高亮匹配文本的方法 highlightMatches(text) { if (!text || typeof text !== 'string' || this.dnNames.length === 0) { return text; } // 创建正则表达式(转义特殊字符) const pattern = new RegExp( this.dnNames .map(name => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) .join('|'), 'gi' ); // 替换匹配文本 return text.replace(pattern, match => ${match} ); }, formatValue(value, fieldName) { if (value === null || value === undefined) return ''; // 医案全文字段特殊处理 if (fieldName === '醫案全文' && typeof value === 'string') { return this.highlightMatches(value); } // 其他字段保持原逻辑 if (typeof value === 'string' && value.startsWith('http')) { return ${value}; } return value; }, // 专门处理dntag字段的显示格式 formatDntagValue(dntagArray) { return dntagArray.map(tagObj => { // 只显示name属性,隐藏id等其他属性 return tagObj.dnname || tagObj.name || '未命名標籤'; }).join(';'); // 使用大写分号分隔 }, sortBy(key) { // 需要从中文名称映射回原始字段名进行排序 const originalKey = Object.keys(this.fieldNames).find( origKey => this.fieldNames[origKey] === key ) || key; this.sortKey = originalKey; this.sortOrders[originalKey] = this.sortOrders[originalKey] * -1; this.saveState(); // 保存状态 }, prevPage() { if (this.currentPage > 1) { this.currentPage--; this.saveState(); // 保存状态 } }, nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.saveState(); // 保存状态 } }, // 实时处理页码输入 handlePageInput() { // 清除之前的定时器 clearTimeout(this.inputTimeout); // 设置新的定时器(防抖处理) this.inputTimeout = setTimeout(() => { this.goToPage(); this.saveState(); // 保存状态 }, 300); // 300毫秒后执行 }, // 跳转到指定页码 goToPage() { // 处理空值情况 if (this.inputPage === null || this.inputPage === undefined || this.inputPage === '') { this.inputPage = this.currentPage; return; } // 转换为整数 const page = parseInt(this.inputPage); // 处理非数字情况 if (isNaN(page)) { this.inputPage = this.currentPage; return; } // 确保页码在有效范围内 if (page < 1) { this.currentPage = 1; } else if (page > this.totalPages) { this.currentPage = this.totalPages; } else { this.currentPage = page; } // 同步输入框显示 this.inputPage = this.currentPage; } }, mounted() { this.restoreState(); // 恢复状态 this.fetchData(); }, // 添加keep-alive生命周期钩子 activated() { console.log('醫案閱讀器被激活'); this.restoreState(); // 恢复状态 }, deactivated() { console.log('醫案閱讀器被停用'); this.saveState(); // 保存状态 } }; </script> <style scoped> .container { max-width: 1200px; margin: 0px; padding: 0px; } .control-panel { margin-bottom: 0px; display: flex; flex-wrap: wrap; gap: 10px; justify-content: flex-end; align-items: center; position: fixed; bottom: 0; left: 0; width: 100%; background-color: #ffd800ff; z-index: 999; padding: 10px 20px; box-sizing: border-box; } .content-area { position: fixed; top: 56px; bottom: 45px; /* 位于底部按钮上方 */ left: 0; width: 100%; background: white; padding: 1px; z-index: 100; overflow-y: auto; } .refresh-btn { padding: 4px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } .refresh-btn:hover { background-color: #45a049; } .search-input { padding: 8px; border: 1px solid #ddd; border-radius: 4px; flex-grow: 1; max-width: 300px; } .pagination-controls { display: flex; align-items: center; gap: 5px; } .page-size-select { padding: 4px; border-radius: 4px; width: 70px; } /* 页码输入框样式 */ .page-input { width: 50px; padding: 4px; border: 1px solid #ddd; border-radius: 4px; text-align: center; } /* 水平记录样式 */ .horizontal-records { display: flex; flex-direction: column; gap: 20px; } .record-card { border: 1px solid #ddd; border-radius: 4px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .record-header { padding: 12px 16px; background-color: #f5f5f5; border-bottom: 1px solid #ddd; } .record-header h3 { margin: 0; font-size: 1.1em; } .record-body { padding: 16px; } .record-field { display: flex; margin-bottom: 12px; line-height: 1.5; } .record-field:last-child { margin-bottom: 0; } .field-name { font-weight: bold; min-width: 120px; color: #555; } .field-value { flex-grow: 1; display: flex; flex-wrap: wrap; gap: 8px; } .dntag-value { display: flex; flex-wrap: wrap; gap: 8px; } .array-value { display: flex; flex-wrap: wrap; gap: 8px; } .no-data { padding: 20px; text-align: center; color: #666; font-style: italic; } button:disabled { opacity: 0.5; cursor: not-allowed; } </style> mreditor.vue代碼: <template> <WangEditor v-model="content" @response="(msg) => content = msg" /> <mreditor1 ref="mreditor1" /> </template> <script> import WangEditor from './WangEditor.vue'; import mreditor1 from './mreditor1.vue'; import LZString from 'lz-string'; export default { name: 'mreditor', // 必须设置组件名称用于keep-alive components: { WangEditor, mreditor1 }, data() { return { content: '', submittedId: null, fetchId: null, dnTags: [], showRawHtml: false, stateVersion: '1.0', autoSaveTimer: null, autoSaveInterval: 30000 // 30秒自动保存 }; }, computed: { highlightedContent() { if (!this.dnTags.length || !this.content) return this.content; const tempEl = document.createElement('div'); tempEl.innerHTML = this.content; const walker = document.createTreeWalker( tempEl, NodeFilter.SHOW_TEXT ); const nodes = []; while (walker.nextNode()) { nodes.push(walker.currentNode); } nodes.forEach(node => { let text = node.nodeValue; let newHtml = text; this.dnTags .slice() .sort((a, b) => b.length - a.length) .forEach(tag => { const regex = new RegExp( this.escapeRegExp(tag), 'g' ); newHtml = newHtml.replace( regex, ${tag} ); }); if (newHtml !== text) { const span = document.createElement('span'); span.innerHTML = newHtml; node.parentNode.replaceChild(span, node); } }); return tempEl.innerHTML; }, displayContent() { if (this.showRawHtml) { return this.escapeHtml(this.content); } return this.highlightedContent; }, displayButtonText() { return this.showRawHtml ? '顯示渲染格式' : '顯示原始標籤'; } }, watch: { // 监听内容变化实现自动保存 content: { handler() { this.debouncedSaveState(); }, deep: true } }, async mounted() { await this.fetchDNTags(); this.restoreState(); this.setupAutoSave(); }, // 添加keep-alive生命周期钩子 activated() { console.log('醫案編輯器被激活'); this.restoreState(); this.setupAutoSave(); }, deactivated() { console.log('醫案編輯器被停用'); this.saveState(); // 离开时保存状态 this.clearAutoSave(); }, beforeDestroy() { this.clearAutoSave(); }, methods: { // HTML转义 escapeHtml(unsafe) { if (!unsafe) return ''; return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); }, // 正则表达式转义 escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }, // 设置自动保存 setupAutoSave() { this.clearAutoSave(); this.autoSaveTimer = setInterval(() => { if (this.content || this.submittedId) { console.log('自动保存状态...'); this.saveState(); } }, this.autoSaveInterval); }, // 清除自动保存 clearAutoSave() { if (this.autoSaveTimer) { clearInterval(this.autoSaveTimer); this.autoSaveTimer = null; } }, // 防抖保存状态 debouncedSaveState() { this.clearAutoSave(); this.autoSaveTimer = setTimeout(() => { this.saveState(); this.setupAutoSave(); }, 2000); }, // 保存当前状态 saveState() { // 获取子组件状态 const formData = this.$refs.mreditor1 ? this.$refs.mreditor1.getFormData() : { }; const state = { version: this.stateVersion, content: this.content, submittedId: this.submittedId, formData: formData, showRawHtml: this.showRawHtml, timestamp: new Date().getTime() }; // 对大内容进行压缩 if (this.content.length > 2000) { try { state.compressed = true; state.content = LZString.compressToUTF16(this.content); } catch (e) { console.error('压缩失败,使用原始数据', e); state.compressed = false; } } sessionStorage.setItem('medicalRecordState', JSON.stringify(state)); }, // 恢复状态 restoreState() { const savedState = sessionStorage.getItem('medicalRecordState'); if (!savedState) return; try { const state = JSON.parse(savedState); if (state.version !== this.stateVersion) { console.warn('状态版本不匹配,跳过恢复'); return; } let content = state.content; if (state.compressed) { try { content = LZString.decompressFromUTF16(content); } catch (e) { console.error('解压失败,使用原始数据', e); } } this.content = content; this.submittedId = state.submittedId; this.showRawHtml = state.showRawHtml; if (this.$refs.mreditor1 && state.formData) { this.$refs.mreditor1.setFormData(state.formData); } console.log('医案状态已恢复'); } catch (e) { console.error('状态恢复失败', e); sessionStorage.removeItem('medicalRecordState'); } }, // 清除保存的状态 clearState() { sessionStorage.removeItem('medicalRecordState'); }, // 切换显示格式 toggleDisplayFormat() { this.showRawHtml = !this.showRawHtml; this.saveState(); }, async fetchDNTags() { try { const response = await fetch('DNTag/?format=json'); const data = await response.json(); this.dnTags = data .map(item => item.dnname) .filter(name => name && name.trim().length > 0); } catch (error) { console.error('获取标签失败:', error); alert('标签数据加载失败,高亮功能不可用'); } }, async fetchById() { if (!this.fetchId) { alert('請輸入有效的醫案ID'); return; } try { const response = await fetch(MRInfo/${this.fetchId}/?format=json); if (response.ok) { const data = await response.json(); if (this.$refs.mreditor1) { this.$refs.mreditor1.formData.mrname = data.mrname || ''; this.$refs.mreditor1.formData.mrposter = data.mrposter || ''; } this.content = data.mrcase || ''; this.submittedId = data.id; this.fetchId = null; await this.fetchDNTags(); this.saveState(); alert('醫案數據加載成功!'); } else if (response.status === 404) { alert('未找到該ID的醫案'); } else { throw new Error('獲取醫案失敗'); } } catch (error) { console.error('Error:', error); alert(獲取醫案失敗: ${error.message}); } }, async submitContent() { if (!this.$refs.mreditor1) return; const formData = this.$refs.mreditor1.getFormData(); const postData = { mrcase: this.content, ...formData }; try { const response = await fetch('MRInfo/?format=json', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData), }); if (response.ok) { const data = await response.json(); this.submittedId = data.id; this.saveState(); alert('醫案提交成功!'); } else { throw new Error('提交失败'); } } catch (error) { console.error('Error:', error); alert(提交失败: ${error.message}); } }, async updateContent() { if (!this.submittedId || !this.$refs.mreditor1) return; const formData = this.$refs.mreditor1.getFormData(); const postData = { mrcase: this.content, ...formData }; try { const response = await fetch(MRInfo/${this.submittedId}/?format=json, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData), }); if (response.ok) { this.saveState(); alert('醫案更新成功!'); } else { throw new Error('更新失败'); } } catch (error) { console.error('Error:', error); alert(更新失败: ${error.message}); } }, async deleteContent() { if (!this.submittedId) return; if (!confirm('確定要刪除這個醫案嗎?')) return; try { const response = await fetch(MRInfo/${this.submittedId}/?format=json, { method: 'DELETE', headers: { 'Content-Type': 'application/json', } }); if (response.ok) { this.clearState(); this.resetAll(); alert('醫案刪除成功!'); } else { throw new Error('刪除失败'); } } catch (error) { console.error('Error:', error); alert(刪除失败: ${error.message}); } }, resetAll() { this.content = ''; this.submittedId = null; this.fetchId = null; this.showRawHtml = false; if (this.$refs.mreditor1) { this.$refs.mreditor1.resetForm(); } this.clearState(); } } }; </script> <style scoped> .wangeditor { flex: 1; padding: 10px; overflow-y: auto; } .right-panel { position: fixed; top: 55px; bottom: 480px; right: 0; width: 30%; background: lightblue; padding: 1px; z-index: 100; overflow-y: auto; } .tag-panel { position: fixed; top: 260px; bottom: 300px; right: 0; width: 30%; background: lightyellow; padding: 10px; z-index: 100; overflow-y: auto; } .content-display { position: fixed; top: 490px; left: 0; width: 70%; bottom: 45px; z-index: 999; background-color: white; overflow-y: auto; padding: 10px; border: 1px solid #eee; white-space: pre-wrap; } .sticky-footer { display: flex; justify-content: flex-end; align-items: center; position: fixed; bottom: 0; left: 0; width: 100%; background-color: #ffd800ff; z-index: 999; padding: 10px 20px; box-sizing: border-box; flex-wrap: wrap; } .sticky-footer > span { margin-left: 5px; display: flex; align-items: center; } .submitted-id { padding: 2px; background-color: #e2f0fd; color: #004085; border-radius: 4px; } .reset-btn { margin-left: 10px; padding: 2px; background-color: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer; } .reset-btn:hover { background-color: #c82333; } .id-input { display: flex; align-items: center; } .id-input input { width: 100px; padding: 2px 5px; margin-right: 5px; border: 1px solid #ccc; border-radius: 4px; } .submit-btn { background-color: #28a745; color: white; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer; } .update-btn { background-color: #007bff; color: white; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer; } .delete-btn { background-color: #dc3545; color: white; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer; } .submit-btn:hover { background-color: #218838; } .update-btn:hover { background-color: #0069d9; } .delete-btn:hover { background-color: #c82333; } </style>



