iframe.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const iframe = document.getElementById("headerIframe");
  2. let observer = null
  3. const backcolor = {
  4. project: { background: '#F6FEF9', color: '#3C86DF', logo: './image/logo.jpg' },
  5. mobile: { background: 'none', color: '#000', logo: './image/logo.jpg' },
  6. about: { background: 'none', color: '#000', logo: './image/logo.jpg' },
  7. dynamic: { background: 'none', color: '#000', logo: './image/logo.jpg' }
  8. }
  9. function removeListener() {
  10. if (observer) {
  11. observer.disconnect();
  12. }
  13. }
  14. function reinitIframe() {
  15. if (iframe) {
  16. console.log('开始执行')
  17. const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
  18. const iframeBody = iframeDocument.body
  19. observer = new MutationObserver(function(mutationsList, observer) {
  20. const bodyHeight = iframeBody.clientHeight;
  21. iframe.style.height = `${bodyHeight + 1}px`;
  22. });
  23. observer.observe(iframeBody, { attributes: true, childList: true, subtree: true });
  24. }
  25. }
  26. function handleScroll() {
  27. const scrollYnma = window.scrollY
  28. const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
  29. let imgElement = iframeDocument.getElementById('logo');
  30. let headerItems = iframeDocument.querySelectorAll('.header-item')
  31. const urls = window.location.href
  32. const filed = urls.match(/\/([^\/]+)\.html$/) && urls.match(/\/([^\/]+)\.html$/)[1];
  33. if(scrollYnma > 1) {
  34. iframe.style.background = '#fff'
  35. imgElement.src = './image/logos.jpg'
  36. iframe.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.2)';
  37. headerItems.forEach(function(item) {
  38. item.style.color = '#000'; // 设置你想要的字体颜色
  39. });
  40. return
  41. }
  42. console.log(backcolor[filed], filed)
  43. iframe.style.background = (backcolor[filed] && backcolor[filed].background) || 'none'
  44. iframe.style.boxShadow = '0 0 0 rgba(0, 0, 0, 0)';
  45. imgElement.src = (backcolor[filed] && backcolor[filed].logo) || './image/logos.png'
  46. headerItems.forEach(function(item) {
  47. item.style.color = (backcolor[filed] && backcolor[filed].color) || '#fff'; // 设置你想要的字体颜色
  48. });
  49. }
  50. // 页面滚动事件
  51. document.addEventListener('scroll', handleScroll);
  52. iframe.onload = function() {
  53. reinitIframe();
  54. handleScroll()
  55. }
  56. window.addEventListener('beforeunload', function() {
  57. removeListener();
  58. document.removeEventListener('scroll', handleScroll);
  59. });
  60. // 设计稿尺寸
  61. function bodyScale() {
  62. var devicewidth = document.documentElement.clientWidth;
  63. var scale = devicewidth / 1920; // 设计稿的尺寸
  64. document.body.style.zoom = scale;
  65. }
  66. window.onload = window.onresize = function () {
  67. bodyScale();
  68. };