最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Call Javascript from Css - Stack Overflow

programmeradmin1浏览0评论

Here is a picture of my menu on the website I am developing. I am trying to make it so that when someone hovers over the list items: Wind, Water or fire, their background change color by random.

For example hovering over Wind:

I am trying to do this in Javascript, CSS and HTML exclusively.

Relevant code:

[class*="Starsignpica-"] {
display: block; 
color: black; 
text-decoration: none; 
padding-left: 8px; 
text-align: left; 
line-height: 200%; 
<!--border:1px solid red;-->
height: 30px; 
background-color: white;
box-shadow: 1px 1px 5px #FFFFFFF;
}

ul.menu1 a.Starsignpica-1{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

ul.menu1 a.Starsignpica-2{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

ul.menu1 a.Starsignpica-3{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

[class*="Starsignpica-"]:hover {
onmouseover ="onmousetop()"; 
background-color: green;
}

<script>

function mouseontop(){
alert("hello"); 
}

</script>

Here is a picture of my menu on the website I am developing. I am trying to make it so that when someone hovers over the list items: Wind, Water or fire, their background change color by random.

For example hovering over Wind:

I am trying to do this in Javascript, CSS and HTML exclusively.

Relevant code:

[class*="Starsignpica-"] {
display: block; 
color: black; 
text-decoration: none; 
padding-left: 8px; 
text-align: left; 
line-height: 200%; 
<!--border:1px solid red;-->
height: 30px; 
background-color: white;
box-shadow: 1px 1px 5px #FFFFFFF;
}

ul.menu1 a.Starsignpica-1{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

ul.menu1 a.Starsignpica-2{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

ul.menu1 a.Starsignpica-3{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

[class*="Starsignpica-"]:hover {
onmouseover ="onmousetop()"; 
background-color: green;
}

<script>

function mouseontop(){
alert("hello"); 
}

</script>
Share Improve this question asked Feb 10, 2017 at 18:14 David David 451 gold badge2 silver badges7 bronze badges 5
  • 3 you can't call javascript code within css, but why don't you use jquery to handle this?? – Shayan Commented Feb 10, 2017 at 18:16
  • I am a beginner and I don't feel like diving into too many languages and approaches if that makes sense. I like to understand my solutions. If it however is the only way, I guess must then. – David Commented Feb 10, 2017 at 18:20
  • 1 There's absolutely no need for jQuery. In any case, you can't call JS from CSS, and there should never be a need either – add a hover handler in JS. – JJJ Commented Feb 10, 2017 at 18:21
  • @JJJ by which you mean a mouseover handler, right? ;) – Heretic Monkey Commented Feb 10, 2017 at 18:24
  • Does the color need to be random? Because otherwise you could simply use the :hover CSS pseudo-class to change the background on hover. – Sebastian Zartner Commented Feb 10, 2017 at 18:47
Add a ment  | 

3 Answers 3

Reset to default 1

No, you cannot call javascript from your css. However, you could add an event listener for each element to set background color to a random value.

Js fiddle example: http://jsbin./lodomaregi/edit?html,css,js,output

Given that you have an element to work with you can simply add an event listener by using the .addEventListener function like so:

// Event handler for mouseover to assign random background color.
myElement.addEventListener('mouseover', function(e) {

  // Sets the current target's (element) background color to green.
  e.target.style.backgroundColor = 'green';
})

Suggested solution to your problem.

// Fetch all elements with the 'menu1' class name.
var elements = document.getElementsByClassName('menu1');

// Loop through the elements and add event listeners for each element
for(var i = 0; i < elements.length; i++) {

  // Event handler for mouseover to assign random background color.
  elements[i].addEventListener('mouseover', function(e) {

    // Assign backgroundColor with random color
    e.target.style.backgroundColor = getRandomColor();
  })

  // Event handler for mouseout to reset the background color.
  elements[i].addEventListener('mouseout', function(e) {

    // Reset background color by assigning it an empty string.
    e.target.style.backgroundColor = '';
  })
}

// Function for getting a random color
function getRandomColor() {
  // List of colors which can be returned by the function.
  var colors = [
    'lightgreen',
    'pink',
    'yellow',
    'blue',
    'purple',
    '#ff0000',
    '#c9c9c9'
  ];

  // Fetch random int value.
  var index = getRandomInt(0, colors.length - 1);

  // Return the color from the colors array using the generated index value.
  return colors[index];
}

// Function for generating a random int value. Taken from: 
// http://stackoverflow./questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Hey dude you need to add a script to your html to do that

function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
    color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

$(".listClassName").hover(function(){
        $(this).css("background-color", getRandomColor());
}

Or to choose from a specific list of colors you can use something like this.

function getRandomColor() {
colors = ['red','green']
return colors[Math.floor(Math.random()*colors.length)];
}

Looking back at this i forgot to change the colour back when you stop hovering over this to do that you would need to do something like

$(".listClassName").mouseout(function(){
    $(this).removeAttr("style");
)};

Calling JS functions from CSS is not possible at the moment.
But you can do this with elmnt.addEventListener.

For example:

for(el of $('menu-random-piece')){
    // ()=>{} is just a ES6 arrow function.
    el.addEventListener('mouseover', () => { el.style.backgroundColor = "#" + ("000000" + Math.floor(Math.random()*16777216).toString(16).toUpperCase()).slice('-6') });
    el.addEventListener('mouseout', () => {  el.style.backgroundColor = "" }); 
}
发布评论

评论列表(0)

  1. 暂无评论