javascript~把div变成一个按钮

时间:2017-04-23 13:52:44

标签: javascript html css

我正在尝试将我的代码放到一个我不允许进行大量更改的页面上;托管该页面的人允许我<script>标记&amp;一个<div>,就是它。

--- page ---
<head>
<script type='text/javascript' src='https://example.com/myJSfile.js'>
</head>
<body>
<div id='mydiv'></div>
</body>
------------

当页面加载时,如何只能自定义mydiv,如何将myJSfile.js变成按钮?

我不能保证会为我加载任何典型的jQuery库, 主持人的网站确实加载了CSS,但我不知道他们的风格结构。也许我必须在某些时候学习它。

如果我的代码需要加载jQuery,我首先要检查它是否已经加载。你会如何专门检查?

如果我需要加载自己的css,那么我必须使用myJSfile.js

动态地加载

myJSfile.js js文件可以是我需要它的任何东西。我完全控制它。

你会怎么做?

请记住,除了myJSfile.js之外,我几乎被锁在网页上的任何内容之外,除了脚本&amp; div标签。

2 个答案:

答案 0 :(得分:3)

使用insertbefore()函数添加新元素,然后添加remove()函数,以删除现有的<div>元素:

// Create a <li> node:
var newItemDocument.createElement("LI");
// Create a text node 
var textnode = document.createTextNode("Water");

// Append the text to <li>:
newItemDocument.appendChild(textnode);
// Get the <ul> element to insert a new node:
var list = document.getElementById("myList");

// Insert <li> before the first child of <ul>:
list.insertBefore(newItemDocument, list.childNodes[0]); 

答案 1 :(得分:-1)

虽然你已经接受了答案,但我想我会花点时间尝试提供一个答案,可以预测你将来要求插入元素的事件监听器的未来要求,也许用公共元素替换多个元素:

// using a named, rather than an anonymous, function in
// order that the same function can be reused multiple
// times:
function replaceElementWith(opts) {

  // these are the default settings:
  let settings = {
    'replaceWhat': '#mydiv',
    'replaceWith': 'button',
    'text': 'this is a button',
    'eventHandlers': null
  };

  // here we iterate over all the keys in the
  // (user-supplied) opts Object to override
  // the defaults; we do this by first retrieving
  // the keys of the opts Object, which returns
  // an Array of those keys, and iterating over
  // that Array using Array.prototype.forEach():
  Object.keys(opts).forEach(

    // here we use an arrow function syntax, since
    // don't need to work with an updated 'this'
    // within the function.
    // key : the current key of the Array of keys,
    // here we update the current key of the
    // settings Object (or add a new key to that
    // Object) to the same value as held in the
    // opts Object:
    key => settings[key] = opts[key]
  );

  // in order to allow you to perform the same replacement
  // on multiple elements, we use document.querySelectorAll()
  // to retrieve all elements matching the supplied CSS
  // selector, and then pass that Array-like NodeList to
  // Array.from(), which converts an Array-like structure to
  // an Array:
  let targets = Array.from(
      document.querySelectorAll(

        // this is the CSS selector passed via the
        // opts.replaceWhat value (here '#mydiv'):
        settings.replaceWhat
      )
    ),

    // here we create a new element according to the value
    // passed via the settings.replaceWith value:
    newElem = document.createElement(
      settings.replaceWith
    ),

    // an empty, uninitialised variable to hold the cloned
    // newElem element within the loop (later):
    clone;

  // we set the textContent of the created Element to be
  // equal to the passed-in text, via the opts.text property:
  newElem.textContent = settings.text;

  // here we iterate over the Array of found elements that
  // are to be replaced:
  targets.forEach(

    // again, using an Arrow function expression:
    target => {

      // here we clone the created-element, along with
      // any child nodes:
      clone = newElem.cloneNode(true);

      // unfortunately Node.cloneNode() doesn't clone
      // event-listeners, so we have to perform this
      // step on every iteration, we first test to
      // see if settings.eventHandlers is a truthy
      // value (so not the default null):
      if (settings.eventHandlers) {

        // if there are eventHandlers, then we retrieve
        // the keys of the settings.eventHandlers
        // Object as above:
        Object.keys(settings.eventHandlers).forEach(

          // using Arrow function again;
          // the keys of this object are the event-types
          // we're listening for and the values are the
          // functions to handle that event, so here
          // we add the 'eventType' as the event,
          // and the 'settings.eventHandlers[eventType]
          // (which retrieves the function) as the handler:
          eventType => clone.addEventListener(eventType, settings.eventHandlers[eventType])
        )
      }

      // here we find the parentNode of the element to be
      // replaced, and use Node.replaceChild() to add the
      // new element ('clone') in place of the target element:
      target.parentNode.replaceChild(clone, target)
    })

}

// calling the function, passing in values:
replaceElementWith({

  // CSS selector to identify the element(s) to be removed:
  'replaceWhat': '#mydiv',

  // the eventHandlers Object to define the
  // created element's event-handling:
  'eventHandlers': {
    // in the form of:
    // 'eventName' : eventHandler
    'click': function(e) {
      e.preventDefault();
      document.location.hash = 'buttonClicked';
      this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
    },
    'mouseenter': function(e) {
      this.style.borderColor = '#f90';
    },
    'mouseleave': function(e) {
      this.style.borderColor = 'limegreen';
    }
  }
});

function replaceElementWith(opts) {
  let settings = {
    'replaceWhat': '#mydiv',
    'replaceWith': 'button',
    'text': 'this is a button',
    'eventHandlers': null
  };

  Object.keys(opts).forEach(
    key => settings[key] = opts[key]
  );

  let targets = Array.from(document.querySelectorAll(settings.replaceWhat)),
    newElem = document.createElement(settings.replaceWith),
    clone;

  newElem.textContent = settings.text;

  targets.forEach(
    target => {
      clone = newElem.cloneNode(true, true);
      if (settings.eventHandlers) {
        Object.keys(settings.eventHandlers).forEach(
          eventType => clone.addEventListener(eventType, settings.eventHandlers[eventType]);
        )
      }
      target.parentNode.replaceChild(clone, target)
    })

}

replaceElementWith({
  'replaceWhat': '#mydiv',
  'eventHandlers': {
    'click': function(e) {
      e.preventDefault();
      document.location.hash = 'buttonClicked';
      this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
    },
    'mouseenter': function(e) {
      this.style.borderColor = '#f90';
    },
    'mouseleave': function(e) {
      this.style.borderColor = 'limegreen';
    }
  }
});
div {
  border: 2px solid #f90;
}

button {
  border: 2px solid limegreen;
}
<div id='mydiv'></div>

JS Fiddle demo

下面的演示与上面的演示完全相同,但这样做可以替换多个元素,并且唯一的变化是函数调用:

replaceElementWith({
  // changed this selector to select by class,
  // rather than id (and added multiple elements
  // to the HTML):
  'replaceWhat': '.mydiv',
  'eventHandlers': {
    'click': function(e) {
      e.preventDefault();
      document.location.hash = 'buttonClicked';
      this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
    },
    'mouseenter': function(e) {
      this.style.borderColor = '#f90';
    },
    'mouseleave': function(e) {
      this.style.borderColor = 'limegreen';
    }
  }
});

function replaceElementWith(opts) {
  let settings = {
    'replaceWhat': '#mydiv',
    'replaceWith': 'button',
    'text': 'this is a button',
    'eventHandlers': null
  };

  Object.keys(opts).forEach(
    key => settings[key] = opts[key]
  );

  let targets = Array.from(document.querySelectorAll(settings.replaceWhat)),
    newElem = document.createElement(settings.replaceWith),
    clone;

  newElem.textContent = settings.text;

  targets.forEach(
    target => {
      clone = newElem.cloneNode(true, true);
      if (settings.eventHandlers) {
        Object.keys(settings.eventHandlers).forEach(
          eventType => clone.addEventListener(eventType, settings.eventHandlers[eventType]);
        )
      }
      target.parentNode.replaceChild(clone, target)
    })

}

replaceElementWith({
  'replaceWhat': '.mydiv',
  'eventHandlers': {
    'click': function(e) {
      e.preventDefault();
      document.location.hash = 'buttonClicked';
      this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
    },
    'mouseenter': function(e) {
      this.style.borderColor = '#f90';
    },
    'mouseleave': function(e) {
      this.style.borderColor = 'limegreen';
    }
  }
});
div {
  border: 2px solid #f90;
}

button {
  border: 2px solid limegreen;
}
<div id='mydiv'></div>

JS Fiddle demo

参考文献: