Vue PC端和移动端适配样式(css样式)

31 篇文章 1 订阅
项目需求:XX项目时间赶,主做PC端,移动端是在原有基础上改动,

在这一基础上,建议直接采用@media 媒体查询大小屏幕进行css调整,通过window.screen.width判断屏幕宽度
在这里插入图片描述
在这里插入图片描述

一、需要一个全局globalMixin.js,判断当前屏幕为移动端还是PC端
export const GlobalMixin = {
	data() {
	    return {
	        isApp: false // true:代表移动端,false:代表PC端
	    }
	},
	created() {
		/** 先判断平台,pc端 or 移动端*/
        this.whichPlatform()
	},
	methods: {
        /** PC端、移动端 判断*/
        whichPlatform() {
            if(window.screen.width < 800) {
                this.isApp = true
            }else {
                this.isApp = false
            }
        }
    }
}
二、在.vue文件中mixins混入globalMixin.js,直接根据 isApp变量修改样式

可以通过 :class:style 改变当前样式,也可根据 @media媒体查询来修改样式

<template>
	<div :class="isApp ? 'red' : 'blue'">
		小屏幕背景颜色为红色,大屏幕背景为蓝色 (可以通过F12检查代码,切换大小屏幕,感受变化)
	</div>
	<div :style="{height: isApp ? '100px' : '300px'}">
		小屏幕最小高度为100px,大屏幕高度为300px (可以通过F12检查代码,切换大小屏幕,感受变化)
	</div>
	<div class="box">
		小屏幕宽度为50%,大屏幕宽度为100% (可以通过F12检查代码,切换大小屏幕,感受变化)
	</div>
	<div class="platform_pc">PC端)改行文字在PC端展示,在移动端消失
	</div>
	<div class="platform_app">
		(移动端)改行文字在移动端展示,在PC端消失
	</div>
</template>
<script>
	import { GlobalMixin } from '@/mixins/globalMixin'
    export default {
        name: 'XXX',
        mixins:[GlobalMixin],
    }
</script>
<style>
	.red{ background: red;}
	.blue{ background: blue;}
	.box{ width: 100%}
//媒体查询 自适应
//PC端
@media screen and (min-width:800px){
  .platform_pc{
    display: block;
  }
  .platform_app{
    display: none;
  }
}
//移动端
@media screen and (max-width:700px){
  .platform_pc{
    display: none;
  }
  .platform_app{
    display: block;
    max-width: 100%;
  }
  .box{ width: 50%;}
}
</style>
  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值