关于 top 给全局增加方法

本文探讨了JavaScript中的全局对象top和Window的区别及应用,详细解析了如何利用jQuery库自定义HTTP请求方法,包括GET、POST以及异步和同步请求的封装,旨在提升前端开发效率。

 top 和 Window  一样 是一个全局的顶级对象 应该是jq里面设置的

下面是打印的

console.log(top)

VM602:1 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

$: ƒ ( selector, context )
alert: ƒ alert()
applicationCache: ApplicationCache {status: 0, oncached: null, onchecking: null, ondownloading: null, onerror: null, …}
atob: ƒ atob()
blur: ƒ ()
btoa: ƒ btoa()
caches: CacheStorage {}
cancelAnimationFrame: ƒ cancelAnimationFrame()
cancelIdleCallback: ƒ cancelIdleCallback()
captureEvents: ƒ captureEvents()
chrome: {loadTimes: ƒ, csi: ƒ}
clearInterval: ƒ clearInterval()
clearTimeout: ƒ clearTimeout()
clientInformation: Navigator {vendorSub: "", productSub: "20030107", vendor: "Google Inc.", maxTouchPoints: 0, hardwareConcurrency: 4, …}
close: ƒ ()
closed: false
confirm: ƒ confirm()
createImageBitmap: ƒ createImageBitmap()
crypto: Crypto {subtle: SubtleCrypto}
customElements: CustomElementRegistry {}
defaultStatus: ""
defaultstatus: ""
devicePixelRatio: 1
document: document
external: External {}
fetch: ƒ fetch()
find: ƒ find()
focus: ƒ ()
frameElement: null
frames: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
getComputedStyle: ƒ getComputedStyle()
getSelection: ƒ getSelection()
history: History {length: 1, scrollRestoration: "auto", state: null}
indexedDB: IDBFactory {}
innerHeight: 969
innerWidth: 543
isSecureContext: true
jQuery: ƒ ( selector, context )
layer: {v: "3.1.1", ie: false, index: 0, path: "http://localhost:63342/a-%E6%A1%8C%E9%9D%A2/ss-jq/js/layer/", config: ƒ, …}
length: 0
localStorage: Storage {length: 0}
location: Location {replace: ƒ, href: "http://localhost:63342/a-%E6%A1%8C%E9%9D%A2/ss-jq/01.html?_ijt=l9tmjq2tqe2dr9bukt137mo2oo", ancestorOrigins: DOMStringList, origin: "http://localhost:63342", protocol: "http:", …}
locationbar: BarProp {visible: true}
matchMedia: ƒ matchMedia()
menubar: BarProp {visible: true}
moveBy: ƒ moveBy()
moveTo: ƒ moveTo()
name: ""
navigator: Navigator {vendorSub: "", productSub: "20030107", vendor: "Google Inc.", maxTouchPoints: 0, hardwareConcurrency: 4, …}
onabort: null
onafterprint: null
onanimationend: null
onanimationiteration: null
onanimationstart: null
onappinstalled: null
onauxclick: null
onbeforeinstallprompt: null
onbeforeprint: null
onbeforeunload: null
onblur: null
oncancel: null
oncanplay: null
oncanplaythrough: null
onchange: null
onclick: null
onclose: null
oncontextmenu: null
oncuechange: null
ondblclick: null
ondevicemotion: null
ondeviceorientation: null
ondeviceorientationabsolute: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
ondurationchange: null
onemptied: null
onended: null
onerror: null
onfocus: null
ongotpointercapture: null
onhashchange: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onlanguagechange: null
onload: null
onloadeddata: null
onloadedmetadata: null
onloadstart: null
onlostpointercapture: null
onmessage: null
onmessageerror: null
onmousedown: null
onmouseenter: null
onmouseleave: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onoffline: null
ononline: null
onpagehide: null
onpageshow: null
onpause: null
onplay: null
onplaying: null
onpointercancel: null
onpointerdown: null
onpointerenter: null
onpointerleave: null
onpointermove: null
onpointerout: null
onpointerover: null
onpointerup: null
onpopstate: null
onprogress: null
onratechange: null
onrejectionhandled: null
onreset: null
onresize: null
onscroll: null
onsearch: null
onseeked: null
onseeking: null
onselect: null
onselectionchange: null
onselectstart: null
onstalled: null
onstorage: null
onsubmit: null
onsuspend: null
ontimeupdate: null
ontoggle: null
ontransitionend: null
onunhandledrejection: null
onunload: null
onvolumechange: null
onwaiting: null
onwebkitanimationend: null
onwebkitanimationiteration: null
onwebkitanimationstart: null
onwebkittransitionend: null
onwheel: null
open: ƒ open()
openDatabase: ƒ ()
opener: null
origin: "http://localhost:63342"
outerHeight: 1040
outerWidth: 1920
pageXOffset: 0
pageYOffset: 0
param: ""
parent: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
performance: Performance {timeOrigin: 1564649978605.885, onresourcetimingbufferfull: null, memory: MemoryInfo, navigation: PerformanceNavigation, timing: PerformanceTiming}
personalbar: BarProp {visible: true}
postMessage: ƒ ()
print: ƒ print()
prompt: ƒ prompt()
queueMicrotask: ƒ queueMicrotask()
releaseEvents: ƒ releaseEvents()
requestAnimationFrame: ƒ requestAnimationFrame()
requestIdleCallback: ƒ requestIdleCallback()
resizeBy: ƒ resizeBy()
resizeTo: ƒ resizeTo()
screen: Screen {availWidth: 1920, availHeight: 1040, width: 1920, height: 1080, colorDepth: 24, …}
screenLeft: 0
screenTop: 0
screenX: 0
screenY: 0
scroll: ƒ scroll()
scrollBy: ƒ scrollBy()
scrollTo: ƒ scrollTo()
scrollX: 0
scrollY: 0
scrollbars: BarProp {visible: true}
self: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
sessionStorage: Storage {length: 0}
setInterval: ƒ setInterval()
setTimeout: ƒ setTimeout()
speechSynthesis: SpeechSynthesis {pending: false, speaking: false, paused: false, onvoiceschanged: null}
ssMethod: {changeUrlParam: ƒ, setArr: ƒ, loadStyles: ƒ, isMobilePhone: ƒ}
status: ""
statusbar: BarProp {visible: true}
stop: ƒ stop()
styleMedia: StyleMedia {type: "screen"}
toolbar: BarProp {visible: true}
top: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
type: "GET"
visualViewport: VisualViewport {offsetLeft: 0, offsetTop: 0, pageLeft: 0, pageTop: 0, width: 543, …}
webkitCancelAnimationFrame: ƒ webkitCancelAnimationFrame()
webkitRequestAnimationFrame: ƒ webkitRequestAnimationFrame()
webkitRequestFileSystem: ƒ ()
webkitResolveLocalFileSystemURL: ƒ ()
webkitStorageInfo: DeprecatedStorageInfo {}
window: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
_http: {asyncGet: ƒ, get: ƒ, asyncPost: ƒ, post: ƒ, async: ƒ}

 给全局增加方法 如下

打印 top或者window

_http:
async: ƒ (url, param, type, callback)
asyncGet: ƒ (url, param, callback)
asyncPost: ƒ (url, param, callback)
get: ƒ (url, param)
post: ƒ (url, param, callback)
arguments: (...)
caller: (...)
length: 3
name: "post"
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: ss-http.js:111
[[Scopes]]: Scopes[2]
__proto__: Object
Infinity: Infinity

/*
 * 描 述:操作类
 */
top._http= (function ($) {
    "use strict";
    var httpCode = {
        success: 200,
        fail: 400,
        exception: 500,
        state:"success"
    };
    var exres = { code: httpCode.exception, info: '通信异常,请联系管理员!' }
    var Dream = {
        asyncGet: function (url, param, callback) {//纠结 这个param 去掉是不是更好
            if ( $.isFunction( param) ) {//如果没有param参数 把param改成callback
                callback = param;
                param = undefined;
            }
            $.ajax({
                url: url,
                data: param,
                type: "GET",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data,status) {
                    // if (data.state == "success") {//判断返回数据是否异常 ps(目前判断方法(data.state == "success")根据目前后台判断标准 )
                    //有些接口是返回一个数组 没有data.state 这里要特殊处理一下
                    if (data.state == httpCode.state || !data.state&&status== httpCode.state) {
                        callback(data);
                    }else {
                        layer.alert(data.message||exres.info, { icon: 5 });//数据异常弹窗
                        callback(null);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {//非200报错
                    layer.alert(exres.info, { icon: 5 });
                    callback(null);
                },
                beforeSend: function () {
                    //发送请求前
                },
                complete: function () {
                    //请求完成时运行的函数(在请求成功或失败之后均调用,即在 success 和 error 函数之后)。
                }
            });
        },
        // get请求方法(同步):url地址,param参数 返回  t同步就简化去掉回调 直接得值
        get: function (url, param) {
            var res = {};
            $.ajax({
                url: url,
                data: param,
                type: "GET",
                dataType: "json",
                async: false,
                cache: false,
                success: function (data,status) {
                    if (data.state == httpCode.state || !data.state&&status== httpCode.state) {
                        res = data;
                    }else {
                        layer.alert(data.message||exres.info, { icon: 5 });//后台管理的异常弹窗
                        res = null;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert(exres.info, { icon: 5 });
                    res = null;
                },
                beforeSend: function () {
                },
                complete: function () {
                }
            });
            return res;
        },
        // post请求方法(异步):url地址,param参数,callback回调函数
        asyncPost: function (url, param, callback) {
            if ( $.isFunction( param) ) {//如果没有param参数 把param改成callback
                callback = param;
                param = undefined;
            }
            $.ajax({
                url: url,
                data: param,
                type: "POST",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data,status) {//有的接口会直接返回数组 没有data.state
                    // console.log(status ) 当前项目不适合用status
                    //!data.state&&status== "success" 判断返回数据为数组或者其他 切 没有其他接口一样有 data.state
                    if (data.state == httpCode.state || !data.state&&status== httpCode.state) {
                        callback(data);
                    }else {
                        layer.alert(data.message||exres.info, { icon: 5 });
                        callback(null);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert(exres.info, { icon: 5 });
                    callback(null);
                },
                beforeSend: function () {
                },
                complete: function () {
                }
            });
        },
        // post请求方法(同步):url地址,param参数,callback回调函数
        post: function (url, param, callback) {
            if ( $.isFunction( param) ) {//如果没有参数 把param改成callback
                callback = param;
                param = undefined;
            }
            $.ajax({
                url: url,
                data: param,
                type: "POST",
                dataType: "json",
                async: false,
                cache: false,
                success: function (data,status) {
                    if (data.state == httpCode.state || !data.state&&status== httpCode.state) {
                        callback(data);
                    }else {
                        layer.alert(data.message||exres.info, { icon: 5 });
                        callback(null);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert(exres.info, { icon: 5 });
                    callback(null);
                },
                beforeSend: function () {
                },
                complete: function () {
                }
            });
        },
        // ajax 异步封装 url 参数 请求类型
        async: function (url, param, type, callback) {
            $.ajax({
                url: url,
                data: param,
                type: type,
                dataType: "json",
                async: true,
                cache: false,
                context: param,
                success: function (data) {
                    if (data.state == httpCode.state || !data.state&&status == httpCode.state) {
                        callback.apply(this, [data]);
                    }
                    else {
                        layer.alert(data.message||exres.info, { icon: 5 });
                        callback.apply(this);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    callback(null);
                    layer.alert(exres.info, { icon: 5 });
                },
                beforeSend: function () {
                },
                complete: function () {
                }
            });
        },


    };
    return Dream;
})(window.jQuery);

 

<think>嗯,用户想了解在Vue中如何给所有页面添加全局水印的方法。之前提供的引用内容分别介绍了两种实现方式:使用vue-watermark插件和自定义watermark.js文件。用户可能需要更具体的步骤指导。 用户可能是前端开发者,正在为Vue项目添加水印功能,可能是出于版权保护或安全考虑。从引用[1]看,使用插件是最快捷的方式;引用[2]则展示了结合后端API动态获取水印内容的方案。 需要重点考虑的是全局性需求——用户强调"所有页面",所以应该推荐在根组件(App.vue)或路由守卫中实现。同时要注意水印的覆盖层级(z-index)和页面重绘时的稳定性(resizeObserver)。 在解释时需区分Vue2和Vue3的差异:Vue3的组合式API更适合用provide/inject实现水印服务注入。对于动态水印(如显示用户名),建议结合Vuex/Pinia状态管理。 安全问题值得提醒:纯前端水印容易被移除,重要场景需配合后端校验。另外提到水印密度和透明度对用户体验的影响也很必要,可以举例说明$0.1$-$0.2$的透明度区间比较理想。 最后生成的拓展问题覆盖了主要技术点:性能影响、动态更新、打印适配和安全防护,这些问题都切中实际开发痛点。 </think>在Vue中实现全局水印功能可通过以下两种主流方案,根据项目需求选择: ### 方案一:使用专用插件(推荐新手) ```bash # 安装 vue-watermark 插件 npm install vue-watermark --save # 或 yarn add vue-watermark ``` **全局配置(在 main.js 中)**: ```javascript import Vue from 'vue' import VueWatermark from 'vue-watermark' Vue.use(VueWatermark, { text: '机密文档', // 默认水印文本 fontSize: 16, // 字号 textColor: 'rgba(0,0,0,0.1)', // 文字颜色及透明度 angle: -30, // 旋转角度 zIndex: 10000 // 确保覆盖所有元素 }) ``` ### 方案二:自定义水印组件(灵活控制) **1. 创建 watermark.js 工具文件**: ```javascript // utils/watermark.js const watermark = { set: (text = '默认水印') => { const canvas = document.createElement('canvas') canvas.width = 300 canvas.height = 200 const ctx = canvas.getContext('2d') ctx.font = '16px Microsoft YaHei' ctx.fillStyle = 'rgba(0, 0, 0, 0.1)' ctx.rotate(-30 * Math.PI / 180) ctx.fillText(text, 50, 120) const url = canvas.toDataURL('image/png') const watermarkDiv = document.createElement('div') watermarkDiv.style.position = 'fixed' watermarkDiv.style.top = '0' watermarkDiv.style.left = '0' watermarkDiv.style.width = '100vw' watermarkDiv.style.height = '100vh' watermarkDiv.style.zIndex = '10000' watermarkDiv.style.pointerEvents = 'none' // 防止遮挡点击 watermarkDiv.style.backgroundImage = `url(${url})` watermarkDiv.id = '__watermark__' document.body.appendChild(watermarkDiv) }, remove: () => { const elem = document.getElementById('__watermark__') elem && document.body.removeChild(elem) } } export default watermark ``` **2. 在根组件 App.vue 中调用**: ```vue <script> import watermark from '@/utils/watermark' export default { mounted() { // 静态水印 watermark.set('公司机密') // 动态获取水印内容(需配置axios) this.$api.getWatermark().then(text => { watermark.set(text) }) }, beforeDestroy() { watermark.remove() // 组件卸载时清除 } } </script> ``` ### 关键细节说明 1. **防篡改机制**: ```javascript // 在watermark.js中添加 setInterval(() => { if (!document.getElementById('__watermark__')) { watermark.set(currentText) // 自动恢复被删除的水印 } }, 2000) ``` 2. **响应式处理**: ```javascript window.addEventListener('resize', () => { watermark.remove() watermark.set(currentText) }) ``` 3. **安全增强**(配合后端): - 水印内容包含用户ID/时间戳 - 后端返回加密水印文本(需前端解密显示) > 两种方案均通过`z-index: 10000`确保覆盖所有页面元素,`pointer-events: none`保证页面操作不受影响[^1][^2]。动态水印方案需注意接口请求时机,建议在路由守卫中实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值